我不熟悉使用tensorflow 2
我对在tensorflow 1中使用keras
很熟悉。我通常使用fit
方法API来训练模型。但是最近在tensorflow 2中,他们引入了渴望执行。因此,我在fit
和tf.GradientTape
的CiFAR-10数据集上实现并比较了一个简单的图像分类器,并分别训练了20个纪元
几次运行后,结果如下
fit
API训练的模型
tf.GradientTape
训练的模型
我不确定为什么模型表现出不同的行为。我想我可能会实施某些错误。我认为在tf.GradientTape
中模型开始更快地过度拟合训练数据集很奇怪
以下是一些摘要
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:, :]))
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
参考
答案 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)