首页 > 解决方案 > 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

标签: pythonnumpydeep-learninglstm

解决方案


与 相比,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。


推荐阅读