gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:59:03 25 4
gpt4 key购买 nike

我正在尝试使用 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) 仅返回一个带有模型名称的 block 。

如何返回模型的图表?

最佳答案

弗朗索瓦·肖莱 (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. 您可以按顺序构建模型/使用函数式 API。
  2. 您将“call”函数包装到函数模型中,如下所示:

类子类(模型):

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

关于python - 绘图模型不显示模型层,仅显示模型名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60416449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com