我正在开发一个项目,我需要使我的 CNN 输出像“Flatten”层的输出一样。 没有分类,只是输入照片特征的向量,我有点迷失了......我知道关于 CNN 结构的一切,但我怎样才能开始用 python 来做这个呢?
最佳答案
另一种选择如下。
假设您有一个 tf Keras 模型(为了简单起见,这里我采用了一个较小的模型)。
>>> model.summary()
Model: "sequential_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense_1 (Dense) (None, 128) 100480
_________________________________________________________________
dense_2 (Dense) (None, 64) 8256
_________________________________________________________________
dense_3 (Dense) (None, 32) 2080
_________________________________________________________________
dense_4 (Dense) (None, 1) 33
=================================================================
Total params: 110,849
Trainable params: 110,849
Non-trainable params: 0
_________________________________________________________________
假设您想要一个 $32$ 长的特征向量,对应于层 dense_3
。
现在您可以创建另一个对象
outputs = model.get_layer('dense_3').output
child_model = tf.keras.Model(inputs = model.inputs, outputs= outputs)
并且您的子模型会按照您的意愿行事。您需要调用
features = child_model.predict(image)
重要说明:如果您打印 model.layers
和 child_model.layers
,您不会感到惊讶,它们在同一时间共享相同的层内存地址。这意味着训练一个层将设置另一个层的权重。
关于python - 我如何使我的 CNN 输出成为特征向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71538321/