绘图模型不显示模型层,仅显示模型名称

Plot model doesn't show layers of model, only the model name

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

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() return,plot_model(model, show_shapes=True, expand_nested=True) return 只有一个带有模型名称的块。

如何 return 我的模型图表?

Francois Chollet 说了以下内容:

You can do all these things (printing input / output shapes) in a Functional or Sequential model because these models are static graphs of layers.

In contrast, a subclassed model is a piece of Python code (a call method). There is no graph of layers here. We cannot know how layers are connected to each other (because that's defined in the body of call, not as an explicit data structure), so we cannot infer input / output shapes.

有两种解决方法:

  1. 要么构建模型 sequentially/using 函数 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