python - IndexError:元组索引超出范围 LSTM 模型:使用 numpy 和索引
问题描述
我正在关注YouTube 教程来学习深度学习(加密预测),但我被错误轰炸了。我调试了很多,但由于我是新手,所以我真的想不出解决这个问题的方法。
我得到错误:
IndexError:元组索引超出范围
on line
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))错误回溯:`回溯(最后一次调用):文件“/Users/usr/PycharmProjects/cryptoPred/main.py”,第 35 行,在 x_train = np.reshape(x_train, (x_train.shape[0], x_train. shape[1], 1)) IndexError: 元组索引超出范围` `
上下文的完整代码:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pandas_datareader as web
import datetime as dt
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.layers import Dense, Dropout, LSTM
from tensorflow.keras.layers import Lambda
from tensorflow.keras.models import Sequential
# loading data from yahoo financial API
crypto_currency = 'BTC'
rl_currency = 'USD'
start = dt.datetime(2016, 1, 1)
end = dt.datetime(2021, 8, 10)
data = web.DataReader(f'{crypto_currency}-{rl_currency}', 'yahoo', start, end)
# preparing data
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data['Close'].values.reshape(-1, 1))
prediction_days = 60
x_train, y_train = np.array([]), np.array([])
print(x_train)
for x in range(prediction_days, len(scaled_data)):
x_train = np.append(x_train, scaled_data[x-prediction_days:x, 0])
y_train = np.append(y_train, scaled_data[x, 0])
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1)) // error line
解决方案
与 相比,np.append
行为不同list.append
。例如看下面的代码
# First What you are doing is like below
x_train, y_train = np.array([]), np.array([])
temp_list = [i for i in range(5)]
for x in range(1, 5):
x_train = np.append(x_train, temp_list, 0)
# After doing this the output is
'''
After doing this the x_train is
array([0., 1., 2., 3., 4., 0., 1., 2., 3., 4., 0., 1., 2., 3., 4., 0., 1.,
2., 3., 4.])
As you can see this is a 1D vector but what you want is a 2D matrix.
You should do it like below
'''
# Pre allocate space for faster editing
x_train = np.zeros((5, 5))
# Now change the value at idx as required
start = 0
for idx, x in enumerate(range(5)):
x_train[idx] = [i for i in range(start, start+5)]
start += 1a
# This will give the output of x_train as below
'''
array([[0., 1., 2., 3., 4.],
[1., 2., 3., 4., 5.],
[2., 3., 4., 5., 6.],
[3., 4., 5., 6., 7.],
[4., 5., 6., 7., 8.]])
'''
现在它是一个二维矩阵,您可以访问它的第二个 idx。
推荐阅读
- bash - 在 osx 上使用 xld 在命令行中拆分 cued 音频文件
- python-3.x - Numpy 数组列表未成功附加所有整数
- ssl - 如何使用从1&1 IONOS上传的private_key.key / ssl_certificate.cer / ssl_certificate_INTERMEDIATE.cer 并配置tomcat服务器
- getsockopt - 如何 printf() 声明和初始化 getsockname() 函数?
- controller - 如何使用 react-hook-forms 切换单选按钮选择?
- python - AttributeError:类型对象“数据库”没有属性“scoreDB”
- python - 如何用空字典初始化类 - Python
- ubuntu - 我无法确认任何 api 正在通过 microk8s 中的 localhost 工作
- snowflake-cloud-data-platform - Snowflake - 删除 Schema 中的所有外键,可能使用 CTE 删除
- django - 如何在 VSCode 终端中激活 python 虚拟环境