索引器错误:运行python 3.9.1时元组索引超出范围

2024-06-01 00:46:03 发布

您现在位置:Python中文网/ 问答频道 /正文

运行我的代码时出错

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)

结果是:

/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

Tags: ortestlennptransformopenpricedataset
1条回答
网友
1楼 · 发布于 2024-06-01 00:46:03

您的切片长度不同,因此X_test不是二维数组,而是一维数组,其中每个条目都是形状不一致的数组

为了方便起见,这里使用较小的阵列演示了此问题:

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

要解决这个问题,您需要确保X_test的原始构造包含所有长度相同的输入子集。例如:

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]]])

相关问题 更多 >