Keras 平行层的连接改变了想要的目标形状

Concatenation of Keras parallel layers changes wanted target shape

我对 Keras 和深度学习有点陌生。我目前正在尝试复制此 paper 但是当我编译第一个模型(没有 LSTM)时,我收到以下错误:

"ValueError: Error when checking target: expected dense_3 to have shape (None, 120, 40) but got array with shape (8, 40, 1)"

模型的描述是这样的:

  1. 输入(长度 T 是设备特定的 window 尺寸)
  2. 带过滤器的并行一维卷积 size 3、5 和 7 分别是stride=1number of filters=32activation type=linearborder mode=same
  3. 连接输出的合并层 平行一维卷积
  4. 密集层,output_dim=128activation type=ReLU
  5. 密集层,output_dim=128activation type=ReLU
  6. 密集层,output_dim=Tactivation type=linear

我的代码是这样的:

from keras import layers, Input
from keras.models import Model

# the window sizes (seq_length?) are 40, 1075, 465, 72 and 1246 for the kettle, dish washer,
# fridge, microwave, oven and washing machine, respectively.

def ae_net(T):
    input_layer = Input(shape= (T,))
    branch_a = layers.Conv1D(32, 3, activation= 'linear', padding='same', strides=1)(input_layer)
    branch_b = layers.Conv1D(32, 5, activation= 'linear', padding='same', strides=1)(input_layer)
    branch_c = layers.Conv1D(32, 7, activation= 'linear', padding='same', strides=1)(input_layer)

    merge_layer = layers.concatenate([branch_a, branch_b, branch_c], axis=1)

    dense_1 = layers.Dense(128, activation='relu')(merge_layer)
    dense_2 =layers.Dense(128, activation='relu')(dense_1)
    output_dense = layers.Dense(T, activation='linear')(dense_2)
    model = Model(input_layer, output_dense)
    return model

model = ae_net(40)
model.compile(loss= 'mean_absolute_error', optimizer='rmsprop')
model.fit(X, y, batch_size= 8)

其中 Xy 是长度为 40 个值的 8 个序列的 numpy arrays。所以 X.shapey.shape(8, 40, 1)。其实就是一批数据。问题是我无法理解输出的形状 (None, 120, 40) 以及这些尺寸的含义。

如您所述,您的形状包含 batch_sizelengthchannels(8,40,1)

你的三个卷积,每个都创建一个像 (8,40,32) 这样的张量。 您在 axis=1 中的串联创建了一个类似于 (8,120,32) 的张量,其中 120 = 3*40.

现在,密集层仅在最后一个维度(在本例中为通道)上起作用,而长度(现在为 120)保持不变。

解决方案

现在看来,您确实希望将长度保留在末尾。所以你不需要任何展平或重塑层。不过,您需要保持长度为 40。

您可能在错误的轴上进行串联。您应该在通道轴(2 或 -1)中串联,而不是长度轴 (1)。

因此,这应该是您的连接层:

merge_layer = layers.Concatenate()([branch_a, branch_b, branch_c])
#or layers.Concatenate(axis=-1)([branch_a, branch_b, branch_c])

这将输出 (8, 40, 96),密集层会将 96 转换成其他东西。