【问题标题】:Is there a way to change variable during call?有没有办法在通话期间更改变量?
【发布时间】:2019-06-22 13:40:18
【问题描述】:

tensorflow2.0有类init和call的格式
例如

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)

model = MyModel()

我的问题是,如果我想改变

> def call(self, x):
>     x = self.conv1(x)
>     x = self.flatten(x)
>     x = self.d1(x)
>     return self.d2(x,activation='relu')

这会导致错误。
如果我想在某些过程中更改属性 我该怎么做?

【问题讨论】:

    标签: keras tensorflow2.0


    【解决方案1】:

    如果你想根据条件改变前向传递的行为,你可以在call方法中添加一个参数。

    从您的示例来看,您似乎想要更改最后一层的激活函数。因此,您可以只使用线性激活函数定义最后一层,并根据条件应用所需的激活函数。

    class MyModel(tf.keras.Model):
      def __init__(self):
        super(MyModel, self).__init__()
        self.conv1 = tf.keras.layers.Conv2D(32, 3, activation='relu')
        self.flatten = tf.keras.layers.Flatten()
        self.d1 = tf.keras.layers.Dense(128, activation='relu')
        # note: no activation = linear activation
        self.d2 = tf.keras.layers.Dense(10)
        # Create two activation layers
        self.relu =  tf.keras.layers.ReLU()
        self.softmax = tf.keras.layers.Softmax()
    
      def call(self, x, condition):
        x = self.conv1(x)
        x = self.flatten(x)
        x = self.d1(x)
        x = self.d2(x)
        # Change the activation depending on the condition
        if condition:
          tf.print("callign with activation=relu")
          x = self.relu(x)
        return self.softmax(x)
    
    model = MyModel()
    
    fake_input = tf.zeros((1, 28, 28, 1))
    
    tf.print("condition false")
    tf.print(model(fake_input, condition=False))
    tf.print("condition true")
    tf.print(model(fake_input, condition=True))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-01
      • 2020-06-09
      • 1970-01-01
      相关资源
      最近更新 更多