【问题标题】:Plot model doesn't show layers of model, only the model name绘图模型不显示模型层,仅显示模型名称
【发布时间】:2020-06-10 11:24:58
【问题描述】:

我正在尝试使用 TensorFlow2 构建一些模型,因此我创建了一个模型类,如下所示:

import tensorflow as tf

class Dummy(tf.keras.Model):
    def __init__(self, name="dummy"):
        super(Dummy, self).__init__()
        self._name = name

        self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
        self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)

    def call(self, inputs, training=False):
        x = self.dense1(inputs)
        return self.dense2(x)

model = Dummy()
model.build(input_shape=(None,5))

现在我想绘制模型,而使用 summary() 返回我所期望的,plot_model(model, show_shapes=True, expand_nested=True) 只返回一个带有模型名称的块。

如何返回模型的图形?

【问题讨论】:

    标签: python python-3.x tensorflow keras tensorflow2.x


    【解决方案1】:

    Francois Chollet 说:

    您可以在一个 功能或顺序模型,因为这些模型是静态图 层数。

    相比之下,子类模型是一段 Python 代码(调用 方法)。这里没有图层图。我们无法知道如何分层 相互连接(因为这是在正文中定义的 调用,而不是作为显式数据结构),因此我们无法推断输入 / 输出形状。

    有两种解决方案:

    1. 您可以按顺序构建模型/使用功能 api。
    2. 您将“call”函数包装到如下所示的函数模型中:

    class Subclass(Model):

    def __init__(self):
        ...
    def call(self, x):
        ...
    
    def model(self):
        x = Input(shape=(24, 24, 3))
        return Model(inputs=[x], outputs=self.call(x))
    
    
    if __name__ == '__main__':
        sub = subclass()
        sub.model().summary()
    

    答案取自这里:model.summary() can't print output shape while using subclass model

    另外,这是一篇好文章阅读:https://medium.com/tensorflow/what-are-symbolic-and-imperative-apis-in-tensorflow-2-0-dfccecb01021

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-08
      • 1970-01-01
      • 2016-06-21
      • 1970-01-01
      • 2022-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多