【tf.keras】tf.keras使用tensorflow中定义的optimizer

tf.keras 使用 tensorflow 中定义的 optimizer,同时如果使用 ReduceLROnPlateau() callbacks,会出现错误 AttributeError: \'TFOptimizer\' object has no attribute \'lr\',通过 TFOptimizer 对 optimizer 进行一层包装即可解决这个问题。

Update:2020/01/11

如果想要在 tf.keras 中使用 AdamW、SGDW 等优化器,请将 TensorFlow 升级到 2.0,之后在 tensorflow_addons 仓库中可以找到该优化器,且可以正常使用,具体参照:【tf.keras】AdamW: Adam with Weight decay -- wuliytTaotao

Update:2019/09/21

在 TensorFlow 1.x 使用 tf.keras 时,请使用 tf.keras.optimizers 里面的优化器,不要使用 tf.train 里面的优化器,不然学习率衰减会出现问题。

使用 tf.keras 过程中,如果要使用 learning rate decay,不要使用 tf.train.AdamOptimizer() 等 tf.train 内的优化器,因为学习率的命名不同,导致 tf.keras 中学习率衰减的函数无法使用,一般都会报错 “AttributeError: \'TFOptimizer\' object has no attribute \'lr\'”,这个时候即使我们对 "lr" 参数赋值,也没有办法在之后过程中更新真正的学习率,即学习率并没有按照你想的那样进行 decay。

在 tensorflow 1.10.0 中,tf.keras.optimizers 中的优化器参数命名和 tf.train 的优化器初参数命名中还不一样,这个时候像 tf.keras 的参数命名和 Keras 一样,使用 tf.keras.optimizers.Adam() 没问题,但使用 tf.train.AdamOptimizer() 就没法在 tf.keras 中学习率衰减。

在 tensorflow 1.14 中,tf.keras.optimizers 中的优化器参数命名和 tensorflow 一致了,但在初始化时都一行命令self._set_hyper(\'learning_rate\', kwargs.get(\'lr\', learning_rate)),这一行命令将lr属性和learning_rate属性绑定,会一起更新,所以 tf.keras 中的优化器可以正常使用 tf.keras 中的 learning rate decay,而此时 tf.train.AdamOptimizer() 及 tf.contrib.opt.AdamWOptimizer() 等优化器还是没法正常使用 tf.keras 中的 learning rate decay。

简言之,在 tf.keras 要使用学习率衰减时,优化器不要选择 tf.train 的,而是要 tf.keras 的。目前为止,两者的转化还不是很好,很容易出问题,发现学习率不能正常 decay 也是要了我的老命。

Update:2019/06/06

我的 tensorflow+keras 版本:

print(tf.VERSION)    # \'1.10.0\'
print(tf.keras.__version__)    # \'2.1.6-tf\'

tf.keras 没有实现 AdamW,即 Adam with Weight decay。论文《DECOUPLED WEIGHT DECAY REGULARIZATION》提出,在使用 Adam 时,weight decay 不等于 L2 regularization。具体可以参见 当前训练神经网络最快的方式:AdamW优化算法+超级收敛L2正则=Weight Decay?并不是这样

keras 中没有实现 AdamW 这个 optimizer,而 tensorflow 中实现了,所以在 tf.keras 中引入 tensorflow 的 optimizer 就好。

如下所示:

import tensorflow as tf
from tensorflow.contrib.opt import AdamWOptimizer

mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(512, activation=tf.nn.relu),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])

# adam = tf.train.AdamOptimizer()

# adam with weight decay
adamw = AdamWOptimizer(weight_decay=1e-4)

model.compile(optimizer=adamw,
              loss=\'sparse_categorical_crossentropy\',
              metrics=[\'accuracy\'])

model.fit(x_train, y_train, epochs=10, validation_split=0.1)
print(model.evaluate(x_test, y_test))

如果只是像上面这样使用的话,已经没问题了。但是如果要加入 tf.keras.callbacks 中的某些元素,如 tf.keras.callbacks.ReduceLROnPlateau(),可能就会出现异常 AttributeError: \'TFOptimizer\' object has no attribute \'lr\'。

以下代码将出现 AttributeError: \'TFOptimizer\' object has no attribute \'lr\',就是因为加入了 tf.keras.callbacks.ReduceLROnPlateau(),其它两个 callbacks 不会引发异常。

import tensorflow as tf
from tensorflow.contrib.opt import AdamWOptimizer

mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(512, activation=tf.nn.relu),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])

# 按照 val_acc 的值来保存模型的参数,val_acc 有提升才保存新的参数
ck_callback = tf.keras.callbacks.ModelCheckpoint(\'checkpoints/weights-improvement-{epoch:02d}-{val_acc:.2f}.hdf5\', monitor=\'val_acc\', mode=\'max\',
                                                verbose=1, save_best_only=True, save_weights_only=True)
# 使用 tensorboard 监控训练过程
tb_callback = tf.keras.callbacks.TensorBoard(log_dir=\'logs\')
# 在 patience 个 epochs 内,被监控的 val_loss 都没有下降,那么就降低 learning rate,新的值为 lr = factor * lr_old
lr_callback = tf.keras.callbacks.ReduceLROnPlateau(patience=3)

adam = tf.train.AdamOptimizer()

# adam with weight decay
# adamw = AdamWOptimizer(weight_decay=1e-4)

model.compile(optimizer=adam,
              loss=\'sparse_categorical_crossentropy\',
              metrics=[\'accuracy\'])

model.fit(x_train, y_train, epochs=10, validation_split=0.1, callbacks=[ck_callback, tb_callback, lr_callback])
print(model.evaluate(x_test, y_test))

(上述代码在 tensorflow 1.10.0 之后的版本会出现莫名其妙的错误,以 tensorflow 1.14.0 举例。)

Traceback (most recent call last):
  File "/Users/wuliytTaotao/PycharmProjects/tmp/AdamOrAdamW.py", line 43, in <module>
    model.fit(x_train, y_train, epochs=10, validation_split=0.1, callbacks=[ck_callback, tb_callback, lr_callback])
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 780, in fit
    steps_name=\'steps_per_epoch\')
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/keras/engine/training_arrays.py", line 363, in model_iteration
    batch_outs = f(ins_batch)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/keras/backend.py", line 3292, in __call__
    run_metadata=self.run_metadata)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1458, in __call__
    run_metadata_ptr)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Error while reading resource variable training/beta2_power from Container: localhost. This could mean that the variable was uninitialized. Not found: Resource localhost/training/beta2_power/N10tensorflow3VarE does not exist.
         [[{{node training/AdamW/update_dense/bias/ResourceApplyAdam/ReadVariableOp_1}}]]

References

当前训练神经网络最快的方式:AdamW优化算法+超级收敛 -- 机器之心

L2正则=Weight Decay?并不是这样 -- 杨镒铭

ReduceLROnPlateau with native optimizer: \'TFOptimizer\' object has no attribute \'lr\' #20619