【问题标题】:TensorFlow 2.0 - Model subclassing : no input dimensionTensorFlow 2.0 - 模型子类化:无输入维度
【发布时间】:2020-05-24 06:04:46
【问题描述】:

我在阅读 TensorFlow 2.0 Tutorial 时遇到了创建 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)

然后定义的模型如何知道从训练数据中预期有多少属性/特征?

谢谢

【问题讨论】:

    标签: python-3.x keras tensorflow2.0 tf.keras tensorflow2.x


    【解决方案1】:

    根据 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-30
      • 1970-01-01
      • 2020-04-10
      • 1970-01-01
      • 2020-05-23
      • 2019-12-16
      • 2021-10-14
      • 1970-01-01
      相关资源
      最近更新 更多