我正在阅读 TensorFlow 2.0 教程,并且遇到了模型子类化来创建 TensorFlow 2.0 模型。
我找到的代码是:
class MyModel(Model):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = Conv2D(32, 3, activation='relu')
self.flatten = Flatten()
self.d1 = Dense(128, activation='relu')
self.d2 = Dense(10, activation='softmax')
def call(self, x):
x = self.conv1(x)
x = self.flatten(x)
x = self.d1(x)
return self.d2(x)
# Create an instance of the model
model = MyModel()
现在,在这段代码中,我的困惑是,代码的作者没有定义输入?
没有-
self.input_layer = Input(
shape = (28, 28)
)
# OR-
self.conv1 = Conv2D(32, 3, activation='relu', input_dim = (28, 28)
定义的模型如何知道从训练数据中期望有多少属性/特征?
谢谢
根据 Francois Chollet 的说法,您的问题的答案如下(关于比较(功能+顺序与模型 API):
您可以在一个程序中执行所有这些操作(打印输入/输出形状) 功能或顺序模型,因为这些模型是静态图 层数。
相比之下,子类化模型是一段 Python 代码(调用 方法)。这里没有图层图。我们无法知道如何层 彼此连接(因为这是在正文中定义的 调用,而不是作为显式数据结构),因此我们无法推断输入/ 输出形状
此处提供了这 3 种类型的更详细说明:https://medium.com/tensorflow/what-are-symbolic-and-imperative-apis-in-tensorflow-2-0-dfccecb01021
此处提供了如何通过混合函数 + 模型子类化 api 来实现此目的的示例(归功于 GitHub 上的 ixez):
import tensorflow as tf
from tensorflow.keras.layers import Input
class MyModel(tf.keras.Model):
def __init__(self):
super().__init__()
self.dense = tf.keras.layers.Dense(1)
def call(self, inputs, **kwargs):
return self.dense(inputs)
def model(self):
x = Input(shape=(1))
return Model(inputs=[x], outputs=self.call(x))
MyModel().model().summary()