开始使用免费开始使用

张量的流动

如果您已经构建了一个模型,可以结合使用 model.layerstensorflow.keras.backend 来创建函数。给定一个有效的输入张量,该函数会返回对应的输出张量。

当我们想获取网络在某个中间层的输出时,这非常有用。

例如,若您获取了网络第 1 层的输入和输出,就可以构建一个 inp_to_out 函数,仅通过第 1 层对给定输入张量执行前向传播,并返回结果。

现在就来实践一下吧!

Banknote Authentication 数据集中的 X_test 和其对应的 model 已预加载。请在控制台输入 model.summary() 查看模型结构。

本练习是课程的一部分

Keras 深度学习入门

查看课程

练习说明

  • 导入 tensorflow.keras.backend,并命名为 K
  • 使用 model.layers 列表获取第 1 层的输入和输出引用。
  • 使用 K.function() 定义一个将 inp 映射到 out 的函数。
  • 打印将 X_test 传入第 1 层后的结果。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Import tensorflow.keras backend
import ____

# Input tensor from the 1st layer of the model
inp = ____.____[____].input

# Output tensor from the 1st layer of the model
out = ____.____

# Define a function from inputs to outputs
inp_to_out = K.function([____], [____])

# Print the results of passing X_test through the 1st layer
print(____([____]))
编辑并运行代码