TransWikia.com

IndexError: tuple index out of range when running python 3.9.1

Stack Overflow Asked by Ahmad Nur Hasybi on February 7, 2021

Error while running my codes

dataset_total = pd.concat((dataset['Open'], dataset_test['Open']), axis = 0)
inputs = dataset_total[len(dataset_total) - len(dataset_test) - 60:].values
inputs = inputs.reshape(-1,1)
inputs = sc.transform(inputs)
X_test = []
for i in range(60, 80):
   X_test.append(inputs[i-60:i, 0])
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
predicted_forex_price = regressor.predict(X_test)
predicted_forex_price = sc.inverse_transform(predicted_forex_price)

The results are :

/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:8:
VisibleDeprecationWarning: Creating an ndarray from ragged nested
sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays
with different lengths or shapes) is deprecated. If you meant to do
this, you must specify ‘dtype=object’ when creating the ndarray

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-110-0e4e370b525c> in <module>()
      7 X_test.append(inputs[i-60:i, 0])
      8 X_test = np.array(X_test)
----> 9 X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
     10 predicted_forex_price = regressor.predict(X_test)
     11 predicted_forex_price = sc.inverse_transform(predicted_forex_price)

IndexError: tuple index out of range

One Answer

Your slices are not the same length, so X_test is not a 2-dimensional array, but rather a 1D array, each entry of which is an array with inconsistent shapes.

Here's a demonstration of the issue using a smaller array for convenience:

inputs = np.arange(3)
X_test = [inputs[i:i + 2] for i in range(3)]

print(X_test)
# [array([0, 1]), array([1, 2]), array([2])]

X_test = np.array(X_test)
print(X_test)
# [array([0, 1]) array([1, 2]) array([2])]

np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
# ---------------------------------------------------------------------------
# IndexError                                Traceback (most recent call last)
# <ipython-input-21-769dc2c0479b> in <module>()
#       6 print(X_test)
#       7 # [array([0, 1]) array([1, 2]) array([2])]
# ----> 8 np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))

# IndexError: tuple index out of range

To fix this, you need to ensure that your original construction of X_test contains subsets of the input that are all the same length. For example:

X_test = [inputs[i:i + 2] for i in range(2)]
X_test = np.array(X_test)
np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
# array([[[0],
#         [1]],

#        [[1],
#         [2]]])

Answered by jakevdp on February 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP