tf 卷积函数 Conv2D & Conv1D
import tensorflow as tf
# 每一张图片的尺寸是 32*32,通道数是 3
image_input = tf.keras.Input(shape=(32, 32, 3), name='img_input')
# 每一个句子20个单词,每个单词向量的长度是10
timeseries_input = tf.keras.Input(shape=(20, 10), name='ts_input')
# 第1个参数表示过滤器的个数(输出的通道数),第2个参数表示2维过滤器的长和宽(tuple2或者整数),output_shape: (30,30,3)
x1 = tf.keras.layers.Conv2D(3, 3)(image_input)
x1 = tf.keras.layers.GlobalMaxPooling2D()(x1) # output_shape: (3,)
# 第1个参数表示过滤器的个数(输出的通道数),第2个参数表示1维过滤器的长和宽(tuple1或者整数),output_shape: (18,3)
x2 = tf.keras.layers.Conv1D(3, 3)(timeseries_input)
x2 = tf.keras.layers.GlobalMaxPooling1D()(x2) # output_shape: (3,)
x = tf.keras.layers.concatenate([x1, x2]) # output_shape: (6,)
score_output = tf.keras.layers.Dense(1, name='score_output')(x) # shape: (1,)
class_output = tf.keras.layers.Dense(5, name='class_output')(x) # shape: (5,)
model = tf.keras.Model(inputs=[image_input, timeseries_input],
outputs=[score_output, class_output])
print(model.summary())
tf.keras.utils.plot_model(model, 'multi_input_and_output_model.png', show_shapes=True,dpi=500)
输出结果:
Model: "model"
__________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
==================================================================================================
img_input (InputLayer) [(None, 32, 32, 3)] 0
__________________________________________________________________________________________________
ts_input (InputLayer) [(None, 20, 10)] 0
__________________________________________________________________________________________________
conv2d (Conv2D) (None, 30, 30, 3) 84 img_input[0][0]
__________________________________________________________________________________________________
conv1d (Conv1D) (None, 18, 3) 93 ts_input[0][0]
__________________________________________________________________________________________________
global_max_pooling2d (GlobalMax (None, 3) 0 conv2d[0][0]
__________________________________________________________________________________________________
global_max_pooling1d (GlobalMax (None, 3) 0 conv1d[0][0]
__________________________________________________________________________________________________
concatenate (Concatenate) (None, 6) 0 global_max_pooling2d[0][0]
global_max_pooling1d[0][0]
__________________________________________________________________________________________________
score_output (Dense) (None, 1) 7 concatenate[0][0]
__________________________________________________________________________________________________
class_output (Dense) (None, 5) 35 concatenate[0][0]
==================================================================================================
Total params: 219
Trainable params: 219
Non-trainable params: 0
__________________________________________________________________________________________________
None