首页 > 解决方案 > tensorflow2如何获取中间层输出

问题描述

我想用tensorflow2实现对图像特征的cnn提取,然后输出到SVM进行分类。有哪些好的方法?我检查了 tensorflow2 的文档,没有很好的解释。谁能指导我?

标签: tensorflow2.0

解决方案


感谢您在上面的澄清答案。我以前写过类似问题的答案。但是您可以通过使用所谓的功能模型 API构建辅助模型来从 tf.keras 模型中提取中间层输出。“函数模型 API”使用tf.keras.Model()。调用函数时,指定参数inputsoutputs. 您可以在参数中包含中间层的输出outputs。请参见下面的简单代码示例:

import tensorflow as tf

# This is the original model.
model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=[28, 28, 1]),
    tf.keras.layers.Dense(100, activation="relu"),
    tf.keras.layers.Dense(10, activation="softmax")])

# Make an auxiliary model that exposes the output from the intermediate layer
# of interest, which is the first Dense layer in this case.
aux_model = tf.keras.Model(inputs=model.inputs,
                           outputs=model.outputs + [model.layers[1].output])

# Access both the final and intermediate output of the original model
# by calling `aux_model.predict()`.
final_output, intermediate_layer_output = aux_model.predict(some_input)

推荐阅读