为什么在tensorflow 2中使用tf.GradientTape进行训练与使用fit API进行训练有不同的行为?

时间:2020-01-14 10:15:37

标签: python tensorflow keras deep-learning tensorflow2.0

我不熟悉使用tensorflow 2

我对在tensorflow 1中使用keras很熟悉。我通常使用fit方法API来训练模型。但是最近在tensorflow 2中,他们引入了渴望执行。因此,我在fittf.GradientTape的CiFAR-10数据集上实现并比较了一个简单的图像分类器,并分别训练了20个纪元

几次运行后,结果如下

  • 使用fit API训练的模型
    • 训练数据集,损失约为0.61-0.65,准确度为76%-80%
    • 验证数据集,损失约为0.8,准确度为72%-75%
  • 使用tf.GradientTape训练的模型
    • 训练数据集,损失约为0.15-0.2,准确度为91%-94%
    • 验证数据集,损失约为1.8-2,准确性为64%-67%

我不确定为什么模型表现出不同的行为。我想我可能会实施某些错误。我认为在tf.GradientTape中模型开始更快地过度拟合训练数据集很奇怪

以下是一些摘要

  1. 使用fit API
model = SimpleClassifier(10)
model.compile(
    optimizer=Adam(),
    loss=tf.keras.losses.CategoricalCrossentropy(),
    metrics=[tf.keras.metrics.CategoricalAccuracy()]
)
model.fit(X[:split_idx, :, :, :], y[:split_idx, :], batch_size=256, epochs=20, validation_data=(X[split_idx:, :, :, :], y[split_idx:, :]))
  1. 使用tf.GradientTape
with tf.GradientTape() as tape:
    y_pred = model(tf.stop_gradient(train_X))
    loss = loss_fn(train_y, y_pred)
    gradients = tape.gradient(loss, model.trainable_weights)
model.optimizer.apply_gradients(zip(gradients, model.trainable_weights))

完整代码可以找到here in Colab

参考

1 个答案:

答案 0 :(得分:0)

tf.GradientTape代码中几乎没有什么可以解决的:
1)trainable_variables不是trainable_weights。您想将梯度应用于所有可训练变量,而不仅是模型权重

# gradients = tape.gradient(loss, model.trainable_weights)
gradients = tape.gradient(loss, model.trainable_variables)

# and

# model.optimizer.apply_gradients(zip(gradients, model.trainable_weights))
model.optimizer.apply_gradients(zip(gradients, model.trainable_variables))

2)从输入张量中删除tf.stop_gradient

with tf.GradientTape() as tape:
#    y_pred = model(tf.stop_gradient(train_X))
    y_pred = model(train_X, training=True)

请注意,我还添加了训练参数。它也应该包含在模型定义中,以包含依赖于phase的图层(例如BatchNormalization和Dropout):

    def call(self, X, training=None):
        X = self.cnn_1(X)
        X = self.bn_1(X, training=training)
        X = self.cnn_2(X)
        X = self.max_pool_2d(X)
        X = self.dropout_1(X)

        X = self.cnn_3(X)
        X = self.bn_2(X, training=training)
        X = self.cnn_4(X)
        X = self.bn_3(X, training=training)
        X = self.cnn_5(X)
        X = self.max_pool_2d(X)
        X = self.dropout_2(X)

        X = self.flatten(X)
        X = self.dense_1(X)
        X = self.dropout_3(X, training=training)
        X = self.dense_2(X)
        return self.out(X)

通过这些很少的更改,我设法获得了更好的分数,与keras.fit的结果相比更具可比性:

[19/20] loss: 0.64020, acc: 0.76965, val_loss: 0.71291, val_acc: 0.75318: 100%|██████████| 137/137 [00:12<00:00, 11.25it/s]
[20/20] loss: 0.62999, acc: 0.77649, val_loss: 0.77925, val_acc: 0.73219: 100%|██████████| 137/137 [00:12<00:00, 11.30it/s]

答案: 不同之处可能是事实,Keras.fit在引擎盖下做了大部分这些事情。

最后,为了清楚和可重复,我使用了部分训练/评估代码:

for bIdx, (train_X, train_y) in enumerate(train_batch):
            if bIdx < epoch_max_iter:
                with tf.GradientTape() as tape:
                    y_pred = model(train_X, training=True)
                    loss = loss_fn(train_y, y_pred)
                    total_loss += (np.sum(loss.numpy()) * train_X.shape[0])
                    total_num += train_X.shape[0]
                    # gradients = tape.gradient(loss, model.trainable_weights)
                    gradients = tape.gradient(loss, model.trainable_variables)
                total_acc += (metrics(train_y, y_pred) * train_X.shape[0])

                running_loss = (total_loss/total_num)
                running_acc = (total_acc/total_num)
                # model.optimizer.apply_gradients(zip(gradients, model.trainable_weights))
                model.optimizer.apply_gradients(zip(gradients, model.trainable_variables))

                pbar.set_description("[{}/{}] loss: {:.5f}, acc: {:.5f}".format(e, epochs, running_loss, running_acc))
                pbar.refresh()
                pbar.update()

和评估之一:

# Eval loop
        # Calculate something wrong here
        val_total_loss = 0
        val_total_acc = 0
        total_val_num = 0
        for bIdx, (val_X, val_y) in enumerate(val_batch):
            if bIdx >= max_val_iterations:
                break
            y_pred = model(val_X, training=False)