【发布时间】:2020-12-11 09:40:43
【问题描述】:
我正在尝试为时间序列数据设置 LSTM 自动编码器/解码器,并在尝试训练模型时不断收到 Incompatible shapes 错误。按照步骤并使用来自this example 的玩具数据。请参阅下面的代码和结果。注意 Tensorflow 版本 2.3.0。
创建数据。将数据放入序列中,以(样本、时间戳、特征)的形式对 LSTM 进行时间化。
timeseries = np.array([[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9],
[0.1**3, 0.2**3, 0.3**3, 0.4**3, 0.5**3, 0.6**3, 0.7**3, 0.8**3, 0.9**3]]).transpose()
timeseries_df = pd.DataFrame(timeseries)
def create_sequenced_dataset(X, time_steps=10):
Xs, ys = [], [] # start empty list
for i in range(len(X) - time_steps): # loop within range of data frame minus the time steps
v = X.iloc[i:(i + time_steps)].values # data from i to end of the time step
Xs.append(v)
ys.append(X.iloc[i + time_steps].values)
return np.array(Xs), np.array(ys) # convert lists into numpy arrays and return
X, y = create_sequenced_dataset(timeseries_df, time_steps=3)
timesteps = X.shape[1]
n_features = X.shape[2]
使用重复向量给出的自动编码器/解码器创建 LSTM 模型并尝试训练模型。
model = Sequential()
model.add(LSTM(128, input_shape=(timesteps, n_features), return_sequences=False))
model.add(RepeatVector(timesteps))
model.add(LSTM(128, return_sequences=True))
model.add(TimeDistributed(Dense(n_features)))
model.compile(optimizer='adam', loss='mse')
model.summary()
model.fit(X, y, epochs=10, batch_size=4)
一直报错:
tensorflow.python.framework.errors_impl.InvalidArgumentError: Incompatible shapes: [4,3,2] vs. [4,2]
[[node gradient_tape/mean_squared_error/BroadcastGradientArgs (defined at <ipython-input-9-56896428cea9>:1) ]] [Op:__inference_train_function_10833]
X 看起来像:
array([[[0.1 , 0.001],
[0.2 , 0.008],
[0.3 , 0.027]],
[[0.2 , 0.008],
[0.3 , 0.027],
[0.4 , 0.064]],
[[0.3 , 0.027],
[0.4 , 0.064],
[0.5 , 0.125]],
[[0.4 , 0.064],
[0.5 , 0.125],
[0.6 , 0.216]],
[[0.5 , 0.125],
[0.6 , 0.216],
[0.7 , 0.343]],
[[0.6 , 0.216],
[0.7 , 0.343],
[0.8 , 0.512]]])
你看起来像:
array([[0.4 , 0.064],
[0.5 , 0.125],
[0.6 , 0.216],
[0.7 , 0.343],
[0.8 , 0.512],
[0.9 , 0.729]])
【问题讨论】:
-
你还能打印X和y的形状吗?
标签: python tensorflow keras deep-learning lstm