Python 在Keras-to-TPU模型中使用tensorflow学习率衰减

Python 在Keras-to-TPU模型中使用tensorflow学习率衰减,python,tensorflow,keras,Python,Tensorflow,Keras,我正在遵循“如何使用TPU免费训练Keras模型x20倍的速度”指南()在google的colab TPU上运行Keras模型。它工作得很好。但是…当我适合我的模型时,我喜欢使用余弦重新开始学习速率衰减。我已经将自己的代码编写为keras回调,但它在这个框架内不起作用,因为tensorflowTFOptimizer类没有可以重置的学习率变量。我看到tensorflow本身在tf.train中有一堆衰减函数,就像tf.train.cosine\u衰减一样,但我不知道如何将它嵌入到我的模型中 以下是

我正在遵循“如何使用TPU免费训练Keras模型x20倍的速度”指南()在google的colab TPU上运行Keras模型。它工作得很好。但是…当我适合我的模型时,我喜欢使用余弦重新开始学习速率衰减。我已经将自己的代码编写为keras回调,但它在这个框架内不起作用,因为tensorflow
TFOptimizer
类没有可以重置的学习率变量。我看到tensorflow本身在
tf.train
中有一堆衰减函数,就像
tf.train.cosine\u衰减一样,但我不知道如何将它嵌入到我的模型中

以下是该博客文章的基本代码。有人有办法吗

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示例,带有回调:

一个选项是手动设置学习率-这里有一个Keras+TPU示例,带有回调:

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

下面的方法似乎有效,其中,
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

这是一个聪明的方法,但在这种情况下不起作用,因为它不会在Tensorflow优化器上运行(在代码中这样说):-(这是一个聪明的方法,但在这种情况下不起作用,因为它不会在Tensorflow优化器上运行(代码中这样说)。:-(