简体   繁体   English

Keras的多通道CNN-LSTM

[英]Multichannel CNN-LSTM in Keras

I've a multidimensional time-series dataset with N features (dimensions). 我有一个具有N个特征(维度)的多维时间序列数据集。 I'm building a CNN-LSTM model that has N input channels (one per feature). 我正在构建一个CNN-LSTM模型,它有N个输入通道(每个功能一个)。 First the model should perform 1D convolutions on each feature, then merge the outputs and feed it to an LSTM layer. 首先,模型应对每个特征执行1D卷积,然后合并输出并将其馈送到LSTM层。 However, I'm having problems with the dimensions (I suspect this is the underlying issue), namely the merged output dimensions are not what expected. 但是,我遇到尺寸问题(我怀疑这是潜在的问题),即合并的输出尺寸不是预期的。

I've tried Flatten() on each feature but it returns (?, ?), and Reshape() doesn't seem to do the trick either. 我已经在每个功能上尝试了Flatten()但它返回(?,?),而Reshape()似乎也没有做到这一点。

# Init the multichannel CNN-LSTM proto.
def mccnn_lstm(steps=window, feats=features, dim=1, f=filters, k=kernel, p=pool):
    channels, convs = [], []

    # Multichannel CNN layer
    for i in range(feats):
        chan = Input(shape=(steps, dim))
        conv = Conv1D(filters=f, kernel_size=k, activation="tanh")(chan)
        maxpool = MaxPooling1D(pool_size=p, strides=1)(conv) # Has shape (?, 8, 64)
        flat = Flatten()(maxpool) # Returns (?, ?), not (?, 8*64) as expected
        channels.append(chan)
        convs.append(flat)

    merged = concatenate(convs)  # Returns (?, ?), would expect a tensor like (?, 8*64, num of channels)

    # LSTM layer
    lstm = TimeDistributed(merged)
    lstm = LSTM(64)(merged) # This line raises the error
    dense = Dense(1, activation="sigmoid")(lstm)

    return Model(inputs=channels, outputs=dense)


model = mccnn_lstm()

Error message: 错误信息:

ValueError: Input 0 is incompatible with layer lstm_1: expected ndim=3, found ndim=2

I'd expect the merged output from the multichannel layer to have dimensions (?, 8*64, num of channels), or something similar, which would then be the input to the LSTM layer. 我希望多通道层的合并输出具有尺寸(?,8 * 64,通道数量)或类似的东西,然后它们将成为LSTM层的输入。

Are you using Keras? 你在用Keras吗? In that case, you didn't create any Sequential() model. 在这种情况下,您没有创建任何Sequential()模型。 That is likely to be a cause of error. 这可能是错误的原因。 Please let me know. 请告诉我。

-- -

EDIT : 编辑

I think Flatten() is not needed in this model. 我认为在这个模型中不需要Flatten() Flatten was meant to feed the output of a conv2D() layer into a Dense() layer, ie to flatten a 2-dimensional object into a 1-dimensional vector. Flatten旨在将conv2D()层的输出馈送到Dense()层,即将二维对象展平为一维向量。 But if you are already working in 1D (with conv1D ) then Flatten() is not needed. 但如果您已经在1D(使用conv1D )工作,则不需要Flatten()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM