为何MinMaxScaler后需对Sequential模型做Reshape?附使用方法及股票预测场景
股票预测中MinMaxScaler后Reshape操作及预测验证代码示例
一、Reshape必要性的直观体现
LSTM等时序模型要求输入数据为**[样本数, 时间步长, 特征数]**的三维格式,若直接用归一化后的二维数组喂模型会报错:
import numpy as np from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM # 模拟开盘价数据(替换为你的df["Open"].values) open_prices = np.array([100, 102, 105, 103, 106, 108, 110, 112, 115, 113]) scaler = MinMaxScaler(feature_range=(0,1)) scaled_data = scaler.fit_transform(open_prices.reshape(-1,1)) # 错误示例:未Reshape直接输入LSTM model = Sequential() model.add(LSTM(50, input_shape=(scaled_data.shape[0],))) # 运行报错:ValueError: Input 0 of layer lstm is incompatible with the layer: expected ndim=3, found ndim=2
二、Reshape的正确使用方法
先构造时序样本,再转换为模型要求的三维格式:
# 设置时间步长(用前3天数据预测第4天) time_steps = 3 # 构造训练集 X_train = [] y_train = [] for i in range(time_steps, len(scaled_data)): X_train.append(scaled_data[i-time_steps:i, 0]) y_train.append(scaled_data[i, 0]) X_train, y_train = np.array(X_train), np.array(y_train) # 关键Reshape操作:转换为[样本数, 时间步长, 特征数] X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1) # 此时X_train形状为(7, 3, 1),符合LSTM输入要求
三、预测准确性验证代码
训练模型后,通过反归一化对比真实值与预测值:
from tensorflow.keras.layers import Dense # 构建并训练模型 model = Sequential() model.add(LSTM(50, return_sequences=False, input_shape=(X_train.shape[1], 1))) model.add(Dense(25)) model.add(Dense(1)) model.compile(optimizer='adam', loss='mean_squared_error') model.fit(X_train, y_train, batch_size=1, epochs=10) # 准备测试输入(用最后3天归一化数据) test_input = scaled_data[-time_steps:] test_input = test_input.reshape(1, time_steps, 1) # 同样需要Reshape # 预测并反归一化 predicted_scaled = model.predict(test_input) predicted_price = scaler.inverse_transform(predicted_scaled) # 对比真实值与预测值 actual_price = open_prices[-1] print(f"真实开盘价: {actual_price}") print(f"预测开盘价: {predicted_price[0][0]:.2f}") # 计算误差指标 mae = np.abs(predicted_price[0][0] - actual_price) print(f"平均绝对误差: {mae:.2f}")
内容的提问来源于stack exchange,提问作者Shreeya Sharma
相关产品推荐
相关产品推荐

