有人能给我详细解释一下这段代码吗,我不明白突出显示的部分。我的意思是他们为什么要写:
x = tf.Keras.layers.Dense(128, activation='relu')(pretrained_model.output)
密集()()后面跟着另一个括号wat可能是原因吗?
完整代码:
inputs = pretrained_model.input
x = tf.keras.layers.Dense(128, activation='relu')(pretrained_model.output)
outputs = tf.keras.layers.Dense(9, activation='softmax')(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
model.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)
在第一行中,您将输入定义为等于预训练模型的输入。然后您将x定义为等于预训练模型的输出(在应用额外的密集层之后)。Tensorflow现在会自动识别输入和x是如何连接的。如果我们假设,预训练模型由五层[pretrained_in,pretrained_h_1,pretrained_h_2,pretrained_h_3,pretrained_out]组成,这意味着TensorFlow意识到,信息将采用以下方式:
投入-
如果我们现在考虑最后几层,我们将有以下信息流:
投入-
现在"model=tf. keras.Model(输入=输入,输出=输出)"语句只是告诉Tensorflow,它应该将这个信息流视为一个新模型,这样您就可以通过使用这个新模型轻松地通过所有这些层传递新信息。
编辑:你问为什么Dense后面有两个括号。Layers. Dense()调用实际上不是处理数据的函数。相反,如果您调用tf.keras.layers.Dense(),则Tensorflow基本上会创建一个新的密集层并将其返回给您,然后您可以使用它来处理您的数据。您实际上可以将其写成两行以使其更清楚:
dense_layer = layers.Dense(128, activation='relu') # We define a new dense layer
dense_layer_output = dense_layer(pretrained_model.output) # We apply the dense layer to the data