在Keras-to-TPU模型中使用TensorFlow学习速率衰减



我正在遵循"如何免费使用TPU训练Keras X20型X 20倍"指南(单击此处),以在Google的Colab TPU上运行KERAS模型。它可以很好地工作。但是...当我适合模型时,我喜欢使用余弦重新启动学习率衰减。我已经将自己的编码作为keras回调编码,但是它在此框架内无法使用,因为TensorFlow TFOptimizer类没有可以重置的学习率变量。我看到TensorFlow本身在tf.train中具有许多衰减功能,例如tf.train.cosine_decay,但我不知道如何将其嵌入模型中。

这是该博客文章的基本代码。有人有修复吗?

import tensorflow as tf
import os
from tensorflow.python.keras.layers import Input, LSTM, Bidirectional, Dense, Embedding
def make_model(batch_size=None):
    source = Input(shape=(maxlen,), batch_size=batch_size,
                   dtype=tf.int32, name='Input')
    embedding = Embedding(input_dim=max_features,
                          output_dim=128, name='Embedding')(source)
    lstm = LSTM(32, name='LSTM')(embedding)
    predicted_var = Dense(1, activation='sigmoid', name='Output')(lstm)
    model = tf.keras.Model(inputs=[source], outputs=[predicted_var])
    model.compile(
        optimizer=tf.train.RMSPropOptimizer(learning_rate=0.01),
        loss='binary_crossentropy',
        metrics=['acc'])
    return model
training_model = make_model(batch_size=128)
# This address identifies the TPU we'll use when configuring TensorFlow.
TPU_WORKER = 'grpc://' + os.environ['COLAB_TPU_ADDR']
tf.logging.set_verbosity(tf.logging.INFO)
tpu_model = tf.contrib.tpu.keras_to_tpu_model(
    training_model,
    strategy=tf.contrib.tpu.TPUDistributionStrategy(
        tf.contrib.cluster_resolver.TPUClusterResolver(TPU_WORKER)))
history = tpu_model.fit(x_train, y_train,
                    epochs=20,
                    batch_size=128 * 8,
                    validation_split=0.2)

一个选项是手动设置学习率 - 这里有一个keras tpu示例,并在此处进行回调:https://github.com/tensorflow/tensorflow/tpu/blob/master/master/models/experimentimy/resnet50_keras/Resnet50.py#l197-l201

以下似乎有效,其中 lr是您选择的初始学习率,而 M是您想要到达余弦衰减工作的初始步骤的数量。

def make_model(batch_size=None,lr=1.e-3,n_steps=2000):
    source = Input(shape=(maxlen,), batch_size=batch_size,
                   dtype=tf.int32, name='Input')
    embedding = Embedding(input_dim=max_features,
                          output_dim=128, name='Embedding')(source)
    lstm = LSTM(32, name='LSTM')(embedding)
    predicted_var = Dense(1, activation='sigmoid', name='Output')(lstm)
    model = tf.keras.Model(inputs=[source], outputs=[predicted_var])
    # implement cosine decay or other learning rate decay here
    global_step = tf.Variable(0)    
    global_step=1
    learning_rate = tf.train.cosine_decay_restarts(
        learning_rate=lr,
        global_step=global_step,
        first_decay_steps=n_steps,
        t_mul= 1.5,
        m_mul= 1.,
        alpha=0.1
    )
    # now feed this into the optimizer as shown below
    model.compile(
        optimizer=tf.train.RMSPropOptimizer(learning_rate=learning_rate),
        loss='binary_crossentropy',
        metrics=['acc'])
    return model

最新更新