【问题标题】:Concatenate two models with tensorflow.keras用 tensorflow.keras 连接两个模型
【发布时间】:2019-07-25 20:59:26
【问题描述】:

我目前正在使用 MNIST 数据集研究用于图像分析的神经网络模型。我首先只使用图像来构建第一个模型。然后我创建了一个附加变量,即: 当数字实际介于 0 和 4 之间时为 0,当它大于或等于 5 时为 1。

因此,我想构建一个可以获取这两个信息的模型:数字的图像,以及我刚刚创建的附加变量。

我创建了两个第一个模型,一个用于图像,一个用于外生变量,如下所示:

import tensorflow as tf
from tensorflow import keras


image_model = keras.models.Sequential()

#First conv layer :
image_model.add( keras.layers.Conv2D( 64, kernel_size=3,
                                               activation=keras.activations.relu,
                                      input_shape=(28, 28, 1) ) )

#Second conv layer :
image_model.add( keras.layers.Conv2D( 32, kernel_size=3, activation=keras.activations.relu ) )

#Flatten layer :
image_model.add( keras.layers.Flatten() )

print( image_model.summary(), '\n' )




info_model = keras.models.Sequential()

info_model.add( keras.layers.Dense( 5, activation=keras.activations.relu, input_shape=(1,) ) )

print( info_model.summary() )

然后我想连接两个最终层,最后放置另一个带有 softmax 的密集层来预测类别概率。

我知道使用 Keras 函数 API 是可行的,但是如何使用 tf.keras 来做到这一点?

【问题讨论】:

  • tf.keras 也有Functional API(同一个API),为什么不用呢?

标签: python tensorflow keras


【解决方案1】:

您可以在 TF 中轻松使用 Keras 的函数式 API(使用 TF 2.0 测试):

import tensorflow as tf

# Image
input_1 = tf.keras.layers.Input(shape=(28, 28, 1))
conv2d_1 = tf.keras.layers.Conv2D(64, kernel_size=3,
                                  activation=tf.keras.activations.relu)(input_1)

# Second conv layer :
conv2d_2 = tf.keras.layers.Conv2D(32, kernel_size=3,
                                  activation=tf.keras.activations.relu)(conv2d_1)

# Flatten layer :
flatten = tf.keras.layers.Flatten()(conv2d_2)

# The other input
input_2 = tf.keras.layers.Input(shape=(1,))
dense_2 = tf.keras.layers.Dense(5, activation=tf.keras.activations.relu)(input_2)

# Concatenate
concat = tf.keras.layers.Concatenate()([flatten, dense_2])

n_classes = 4
# output layer
output = tf.keras.layers.Dense(units=n_classes,
                               activation=tf.keras.activations.softmax)(concat)

full_model = tf.keras.Model(inputs=[input_1, input_2], outputs=[output])

print(full_model.summary())

给你the model you are looking for.

【讨论】:

  • 完美答案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多