当只传递网络的输入和输出时,keras函数API模型如何知道层

2024-05-06 01:27:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我不熟悉Keras,也不了解函数api模型结构

一,- 如前所述here in docskeras.Model只接受输入和输出参数,层列在模型前面。有人能告诉我keras.Model如何知道层结构和输入输出之间的多层结构,而我们只传递输入和输出数组

二,- 另外,什么是layers.outputlayers.input的输出。输出不是一个简单的张量吗?当我打印layers.output时,我看到了下面的输出,它使用来自this example的语法用于其他层。看起来layers.output和layers.input也包含层信息,如dense_5/Relu:0。有人能澄清以下输出的组成部分代表什么吗

print [layer.output for layer in model.layers]

输出:

 [<tf.Tensor 'input_6:0' shape=(None, 3) dtype=float32>,
  <tf.Tensor 'dense_5/Relu:0' shape=(None, 4) dtype=float32>,
  <tf.Tensor 'dense_6/Softmax:0' shape=(None, 5) dtype=float32>]

Tags: in模型noneinputoutputmodellayerstf
2条回答

为了回答您关于模型如何知道中间张量上调用的层的第一个问题,我认为看一下help(keras.Input)会很有帮助:

Input() is used to instantiate a Keras tensor.

A Keras tensor is a symbolic tensor-like object, which we augment with certain attributes that allow us to build a Keras model just by knowing the inputs and outputs of the model.

因此,基本上,Keras使用Python在引擎盖下做一些魔术

每次在Keras张量上调用Keras层时,它都会输出一个Keras张量,该张量已根据层的功能进行了数学转换,但也会将有关该层的一些信息添加到此Keras张量中(在对象的Python属性中)

  1. 在编译/拟合/评估之前,您应该首先描述模型。创建一个序列:第一层是输入层,接下来是一组中间层,然后是输出层

比如你的例子:

inputs = keras.Input(shape=(784,))          # input layer
dense = layers.Dense(64, activation="relu") # describe a dense layer
x = dense(inputs)                           # set x as a result of dense layer with inputs
x = layers.Dense(64, activation="relu")(x)  # "update" x with next layer which has previous dense layer as input
outputs = layers.Dense(10)(x)               # set your output
model = keras.Model(inputs=inputs, outputs=outputs, name="mnist_model") # incorporate all layers in a model

所以基本上Keras已经知道模型内部是什么

  1. 您正在考虑获取中间层的输出。这是迁移学习(当您使用预先训练的模型作为特征提取器时)或某些体系结构作为跳过连接时的常见原则。在这种情况下,您将获得多个输出。此外,根据模型用途,网络在模型末尾可以有多个输出。在您的示例中,它们仅用于演示目的,没有任何意义。看看更有意义的feature extraction

相关问题 更多 >