【问题标题】:Keras functional api: Input is incompatible with the layer with conv1dKeras功能api:输入与conv1d层不兼容
【发布时间】:2020-03-12 14:11:54
【问题描述】:

我有一个大型工作模型,我想将最后一个密集层更改为卷积层(带有池化和输出)。但是使用 cnn 时出现以下错误:

ValueError: 层 conv1d_21 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=2。收到的完整形状:[无,768]

这是在尝试使用 cnn 之前最后一层的样子:

dense = model.get_layer('NSP-Dense').output
outputs = keras.layers.Dense(len(100), activation='sigmoid')(dense)

这是使用 CNN 时的样子以及发生错误的位置(在第二行):

dense = model.get_layer('NSP-Dense').output
conv = keras.layers.Conv1D(filters=32, kernel_size=8, activation='relu')(dense)
pooling = keras.layers.MaxPooling1D(pool_size=2)(conv)
flatten = keras.layers.Flatten()(pooling)
mid_dense = keras.layers.Dense(400, activation='relu' )(flatten)
outputs = keras.layers.Dense(len(test_y[0]), activation='sigmoid')(mid_dense)

我读过thisthis 之类的问题,但我的问题似乎是另一个问题,因为CNN 不是第一层而是位于网络的中间。

NSP-Dense 层的输出形状为 (None, 768)。我尝试将转换层中的形状设置为input_shape =(None, 768)input_shape =(None, 768, 1),但这并没有解决问题。有人有想法吗?

【问题讨论】:

    标签: python keras conv-neural-network


    【解决方案1】:

    我根据您的代码整理了这个示例,这似乎避免了错误。这可能会让你指向正确的方向。请注意 Reshape 层,它本质上添加了一个大小为 1 的虚拟三维,以解决来自 Conv1D 层的问题。我希望这会有所帮助。

    import tensorflow as tf
    
    myInput = tf.keras.layers.Input(shape=(2,))
    myOutput = tf.keras.layers.Dense(768,name='NSP-Dense')(myInput)
    model = tf.keras.models.Model(myInput,myOutput)
    model.summary()
    
    newDense = model.get_layer('NSP-Dense').output
    newReshape = tf.keras.layers.Reshape((768,1), name='newReshape')(newDense)
    conv =  tf.keras.layers.Conv1D(filters=32, kernel_size=8, activation='relu', name='newModelConv1D' )(newReshape)
    newModel = tf.keras.models.Model(myInput, conv)
    newModel.summary()
    
    import numpy as np
    x_train = np.random.random((5,2))  # 5 samples
    print('prediction:')
    newModel.predict(x_train)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-06
      • 1970-01-01
      • 2022-07-13
      • 2019-03-06
      相关资源
      最近更新 更多