You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

股票价格预测LSTM代码报错:AttributeError与IndexError求助

解决TSLA股票LSTM预测模型的两个报错问题

第一个报错:AttributeError: 'list' object has no attribute 'shape'

原因

初始代码中x_train是Python原生列表,列表对象没有shape属性,但Keras的LSTM层需要通过数组的shape来确定输入维度,因此触发该错误。

错误尝试的问题

你用np.append将x_train转为numpy数组的方式,会把原本的二维序列结构(每个样本是60个时间步的数据)压缩成一维数组,直接导致后续访问维度时出错。

第二个报错:IndexError: tuple index out of range

原因

通过np.append构建的x_train是一维numpy数组,仅包含shape[0](总元素数)这一个维度,没有shape[1],因此访问x_train.shape[1]时触发索引越界。

正确解决方法

正确流程是:先通过列表收集序列数据,再转为numpy数组,最后调整数组维度以匹配LSTM的输入要求(输入格式为(样本数量, 时间步长, 特征数量))。

修正后的完整代码

import pandas as pd
import yfinance as web
import numpy as np

from sklearn.preprocessing import MinMaxScaler
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense, Dropout
from tensorflow.python.keras.layers.recurrent import LSTM

company = 'TSLA'
start='2012-01-01'
end='2024-03-01'

data = web.download(company, start=start, end=end)

scaler = MinMaxScaler(feature_range=(0,1))
scaled_data = scaler.fit_transform(data['Close'].values.reshape(-1,1))

prediction_days = 60

x_train = []
y_train = []

# 按原逻辑收集序列数据
for x in range(prediction_days, len(scaled_data)):
    x_train.append(scaled_data[x-prediction_days:x, 0])
    y_train.append(scaled_data[x, 0])

# 将列表转为numpy数组
x_train, y_train = np.array(x_train), np.array(y_train)

# 调整维度适配LSTM输入:(样本数, 时间步长, 特征数)
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))

model = Sequential()

# 此时x_train.shape[1]为时间步长60,输入维度合法
model.add(LSTM(units = 50, return_sequences=True, input_shape=(x_train.shape[1], 1)))
model.add(Dropout(0.2))
model.add(LSTM(units = 50, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units = 50))
model.add(Dropout(0.2))
# 补充输出层(原代码缺失,否则模型无法完成预测)
model.add(Dense(units=1))

关键修正点

  1. 保留原列表收集序列的逻辑,避免破坏数据的二维结构
  2. 转numpy数组后,通过np.reshape将x_train从(样本数, 60)调整为(样本数, 60, 1),满足LSTM对三维输入的要求
  3. 补充最后的Dense输出层,确保模型具备预测输出的能力

内容的提问来源于stack exchange,提问作者Subbsos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 11:55:05