多层感知器的Keras vs TensorFlow2实现

时间:2019-12-05 18:55:28

标签: python tensorflow machine-learning keras deep-learning

我具有以下简单的多层感知器模型的实现,如下所示:

from keras.models import Model 
from keras.layers import Input 
from keras.layers import Dense 
from keras.utils import plot_model

visible = Input(shape=(10,))
hidden1 = Dense(10, activation='relu')(visible)
hidden2 = Dense(20, activation='relu')(hidden1)
hidden3 = Dense(10, activation='relu')(hidden2)
output = Dense(1, activation='sigmoid')(hidden3)

my_model_keras = Model(inputs=visible, outputs=output)

和plot_model()函数返回以下图形:

some additional languages

然后我尝试在Tensorflow2中实现以下相同模型:

import tensorflow as tf

class TensorflowModel(tf.keras.Model):
    def __init__(self):
        super(TensorflowModel, self).__init__()

        self.visible = tf.keras.layers.Input(shape=(10,))
        self.hidden1 = tf.keras.layers.Dense(10)
        self.hidden2 = tf.keras.layers.Dense(20)
        self.hidden3 = tf.keras.layers.Dense(10)
        self.final = tf.keras.layers.Dense(1)

    def call(self, x, training=False):
        x = self.visible(x)
        x = tf.nn.relu(x)
        x = self.hidden1(x)
        x = tf.nn.relu(x)
        x = self.hidden2(x)
        x = tf.nn.relu(x)
        x = self.hidden3(x)
        x = tf.nn.relu(x)
        x = self.final(x)

        return tf.nn.sigmoid(x)

my_model_tf = TensorflowModel()

但是,plot_model()函数返回此图(与上图不同):

enter image description here

我的Tensorflow2模型实现有问题吗?

1 个答案:

答案 0 :(得分:0)

型号应该相同。我怀疑图中的差异是由于您使用的是tf.nn操作,而不是第一个实现中的图层激活。因此,plot_model实现可能不会将密集层节点解释为相邻的。