IndexError:运行python 3.9.1时元组索引超出范围
Posted
技术标签:
【中文标题】IndexError:运行python 3.9.1时元组索引超出范围【英文标题】:IndexError: tuple index out of range when running python 3.9.1 【发布时间】:2021-04-21 19:56:11 【问题描述】:运行我的代码时出错
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, (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
【问题讨论】:
您可以打印 X_test 并将其添加到上面的问题中吗? 我该怎么做? 【参考方案1】:您的切片长度不同,因此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]]])
【讨论】:
它有效,但给我警告如 . .警告:tensorflow:模型是用形状 (None, 60, 1) 构造的输入 KerasTensor(type_spec=TensorSpec(shape=(None, 60, 1), dtype=tf.float32, name='lstm_4_input'), name=' lstm_4_input', description="created by layer 'lstm_4_input'"),但它是在形状不兼容的输入上调用的 (None, 2, 1)以上是关于IndexError:运行python 3.9.1时元组索引超出范围的主要内容,如果未能解决你的问题,请参考以下文章
findspark.init() IndexError: 列表索引超出范围错误
IndexError:使用 py2exe 时元组索引超出范围
Python:IndexError:列表索引超出范围 Caeser Cipher