【问题标题】:Tensorflow 2.0 keras fit overrides the "training" parameter in call functionTensorflow 2.0 keras fit 覆盖调用函数中的“训练”参数
【发布时间】:2019-05-15 18:39:34
【问题描述】:

使用 tensorflow 2.0 创建模型时,我会得到两种不同的行为,具体取决于我进行前向传递的方式:

1) 如果我使用model(X) 进行前向传递,那就没问题了,调用方法中的“训练”参数正常工作

对比

2) 如果我使用 model.fit(X, y) 来运行模型,那么“training”参数似乎会被覆盖并设置为 None,无论其默认值是 True 还是 False。

有人知道为什么会这样吗?例如,这意味着我无法设置模型,以便仅当训练设置为 True 时才会发生丢失。

!pip install tensorflow-gpu==2.0.0-alpha0
import tensorflow as tf
from tensorflow.keras.layers import Dense, Flatten, Conv2D
from tensorflow.keras import Model

X = np.random.random((250, 5))
y = X[:, 0] > 0 * 1.0

class MyModel(Model):

  def __init__(self):
    super(MyModel, self).__init__()
    self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
    self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)
    self.dropout = tf.keras.layers.Dropout(0.5)

  def call(self, inputs, training=True):
    print("Training ", training)
    x = self.dense1(inputs)
    if training:
      x = self.dropout(x, training=training)
    return self.dense2(x)

model = MyModel()

然后按预期打印出 Training True

model(X)    # prints out: Training True

但这会打印出 Training None 吗?

model.compile(optimizer='adam', loss='mse')        
model.fit(X, y, epochs=1)   # prints out: Training None

【问题讨论】:

    标签: tensorflow tensorflow2.0


    【解决方案1】:

    这是一个错误:

    tf.keras.Model.call() 的训练值变为 None 时 tf.keras.Model.fit()。 (tf2.0.0-alpha0)

    https://github.com/tensorflow/tensorflow/issues/27275

    【讨论】:

      【解决方案2】:

      此问题已在新发布的 TF2.0 中解决。

      请将上述代码中的!pip install tensorflow-gpu==2.0.0-alpha0 替换为!pip install tensorflow-gpu==2.3。请查看gist here。谢谢!

      输出如下所示。

      model.compile(optimizer='adam', loss='mse')        
      model.fit(X, y, epochs=1)   # prints out: Training None
      
      Training  True
      Training  True
      8/8 [==============================] - 0s 1ms/step - loss: 0.6448
      <tensorflow.python.keras.callbacks.History at 0x7f1f5961edd8>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-15
        • 2019-08-05
        • 2020-07-13
        • 2020-09-23
        • 1970-01-01
        相关资源
        最近更新 更多