连接两层

时间:2019-08-26 21:45:57

标签: python tensorflow keras concatenation conv-neural-network

当我尝试从两层连接结果时,我遇到了一条错误消息。

def cnn_model_fn(learning_rate):
    """Model function for CNN."""
    model1=Sequential()

      # Convolutional Layer #1
    model1.add(tf.keras.layers.Conv2D(
          filters=20,
          kernel_size=[10, 1],
          kernel_initializer='he_uniform',
          bias_initializer=keras.initializers.Constant(value=0),
          padding="same",
          activation=tf.nn.relu, input_shape=(410,1,3)))
    model1.add(Flatten())

    model2=Sequential()

    model2.add(tf.keras.layers.Conv2D(
          filters=20,
          kernel_size=[10, 1],
          kernel_initializer='he_uniform',
          bias_initializer=keras.initializers.Constant(value=0),
          padding="same",
          activation=tf.nn.relu, input_shape=(410,1,3)))
    model2.add(Flatten())

    model4=Sequential()
    model4.add(keras.layers.Concatenate(axis=-1)([model1, model2]))

    optimizer = tf.train.AdamOptimizer(learning_rate)
    model4.compile(loss='mean_squared_error',
                optimizer=optimizer,
                metrics=['mean_absolute_error', 'mean_squared_error'])

    return model4

model4=cnn_model_fn(0.1) 
model4.summary()
  

“ / usr / local / lib / python3.6 / site-packages / tensorflow / python / keras / layers / merge.py   在构建中(self,input_shape)       377#仅用于形状验证。       378,如果不是isinstance(input_shape,list)或len(input_shape)<2   -> 379提高ValueError('Concatenate层应称为'       380'在至少2个输入的列表上')       381 if all([input_shape中shape不为shape):

     

ValueError:应该在的列表上调用Concatenate层   至少2个输入”

1 个答案:

答案 0 :(得分:1)

您正在尝试串联2个模型,但是您想要串联2个层。尝试以下代码。

from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Flatten, Input

def cnn_model_fn(learning_rate):
    """Model function for CNN."""
    input_layer=Input(shape=(410,1,3))

    x1 = (tf.keras.layers.Conv2D(
          filters=20,
          kernel_size=[10, 1],
          kernel_initializer='he_uniform',
          bias_initializer=keras.initializers.Constant(value=0),
          padding="same",
          activation=tf.nn.relu ))(input_layer)
    x1 = Flatten()(x1)

    x2 = (tf.keras.layers.Conv2D(
          filters=20,
          kernel_size=[10, 1],
          kernel_initializer='he_uniform',
          bias_initializer=keras.initializers.Constant(value=0),
          padding="same",
          activation=tf.nn.relu))(input_layer)
    x2 = Flatten()(x2)

    x = (keras.layers.Concatenate(axis=-1)([x1,x2]))

    model = Model(input_layer, x)
    optimizer = tf.train.AdamOptimizer(learning_rate)
    model.compile(loss='mean_squared_error',
                optimizer=optimizer,
                metrics=['mean_absolute_error', 'mean_squared_error'])

    return model