【问题标题】:How to print the data from the output of a keras layer?如何从 keras 层的输出中打印数据?
【发布时间】:2020-04-24 10:07:11
【问题描述】:

我想查看keras 模型每一层的输出。到目前为止,我有这样的东西

for layer in model.layers:
  print(layer.output)

我得到这样的输出:

Tensor("word_input_6:0", shape=(None, 198), dtype=int32)
Tensor("embedding_6/Identity:0", shape=(None, 198, 100), dtype=float32)
Tensor("lstm/Identity:0", shape=(None, 100), dtype=float32)
Tensor("main_output_8/Identity:0", shape=(None, 6), dtype=float32)

但我想看看张量里面是什么。有什么办法可以看到吗?

【问题讨论】:

    标签: tensorflow keras lstm tensorflow2.0


    【解决方案1】:

    有几个选项可以获取每一层的输出。你可以。
    (1) 定义一个 keras 函数并为每一层评估它,或者。
    (2) 定义一个函数模型并运行predict方法得到输出。

    有关这些方法的更多详细信息,请参阅此 stackoverflow_question (Keras, How to get the output of each layer?)

    根据您的要求,您可以选择其中任何一种。我选择了第一个并用简单的 mnist 示例进行了演示。完整示例代码here

    #Getting output of each layer
    from tensorflow.keras import backend as K
    
    inp = model.input                                           # input 
    outputs = [layer.output for layer in model.layers]          # all layer outputs
    functors = [K.function([inp], [out]) for out in outputs]    # evaluation functions
    
    # Testing
    test = test = x_test[1]
    count = 0
    for func in functors:
      print('\n')
      print("Layer Name: ",layer_names[count])
      print('\n')
      print(func([test]))
      count+=1
    

    【讨论】:

    • 什么是 x_test?
    • x_test 是 mnist 数据的测试样本。完整示例在我的回复中的附加代码中(最后)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多