在Keras-to-TPU模型中使用张量流学习率衰减

时间:2019-03-14 13:04:48

标签: python tensorflow keras

我正在遵循“如何免费免费使用TPU训练Keras模型x20倍”指南(click here)在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)

2 个答案:

答案 0 :(得分:0)

一种选择是手动设置学习率-这里有一个Keras + TPU示例,其中有一个回调:https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py#L197-L201

答案 1 :(得分:0)

以下似乎有效,其中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