微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

IndexError:运行python 3.9.1时元组索引超出范围

如何解决IndexError:运行python 3.9.1时元组索引超出范围

运行我的代码时出错

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:从不规则的嵌套创建一个 ndarray 序列(这是一个列表或元组的列表或元组ndarrays 不同的长度或形状)已被弃用。如果你打算做 这个,你必须在创建 ndarray 时指定 'dtype=object'

---------------------------------------------------------------------------
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,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

解决方法

你的切片长度不一样,所以 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,2]) array([2])]
# ----> 8 np.reshape(X_test,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,1))
# array([[[0],#         [1]],#        [[1],#         [2]]])

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。