不兼容形状:带自动编码器的Tensorflow/Keras顺序LSTM

2021-12-01 12:19:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为时间序列数据设置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]]])

y看起来像:

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]])