ValueError: Can not squeeze dim[1], expected a dimension of 1, got 60 for '{{node Squeeze}} = Squeeze[T=DT_FLOAT, squeeze_dims=[-1]]

ValueError: Can not squeeze dim[1], expected a dimension of 1, got 60 for '{{node Squeeze}} = Squeeze[T=DT_FLOAT, squeeze_dims=[-1]]

我目前正在构建一个 LSTM 模型来预测未来 60 天的收盘价。当我尝试拟合模型时出现以下错误: ValueError:无法挤压 dim[1],预期尺寸为 1,'{{node Squeeze}} = SqueezeT=DT_FLOAT, squeeze_dims=[-1]' 的输入形状为 60: [?,60].

下面是我的代码

model = Sequential()
model.add(LSTM(64, activation='tanh', recurrent_activation='sigmoid', input_shape=(x_train.shape[1], x_train.shape[2]),
               return_sequences=True))
model.add(LSTM(256, activation='tanh', recurrent_activation='sigmoid', return_sequences=False))
model.add(Dense(128))
model.add(Dropout(0.2))
model.add(Dense(y_train.shape[1]))
model.compile(optimizer=Adam(learning_rate=0.0001), loss='mse', metrics=['accuracy'])
model.summary()

history = model.fit(x_train, y_train, epochs=20, batch_size=16, validation_split=0.2, verbose=1)

x_train 形状 = (2066,300,2) y_train 形状 = (2066, 60, 1) 所以我使用 300 天的数据(2 个特征)来预测接下来 60 天的收盘价。我不确定为什么会收到此错误并想寻求帮助。

您缺少 y_train 的最后一个维度。只需重塑输出以匹配 y_train:

的尺寸
import tensorflow as tf

x_train = tf.random.normal((2066, 300, 2))
y_train = tf.random.normal((2066, 60, 1))
model = tf.keras.Sequential()
model.add(tf.keras.layers.LSTM(64, activation='tanh', recurrent_activation='sigmoid', input_shape=(x_train.shape[1], x_train.shape[2]),
               return_sequences=True))
model.add(tf.keras.layers.LSTM(256, activation='tanh', recurrent_activation='sigmoid', return_sequences=False))
model.add(tf.keras.layers.Dense(128))
model.add(tf.keras.layers.Dropout(0.2))
model.add(tf.keras.layers.Dense(y_train.shape[1]))
model.add(tf.keras.layers.Reshape((y_train.shape[1], y_train.shape[2])))
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001), loss='mse', metrics=['accuracy'])
model.summary()

history = model.fit(x_train, y_train, epochs=1, batch_size=16, validation_split=0.2, verbose=1)