【问题标题】:How to use tf.train.ExponentialMovingAverage in keras model in tensorflow2.0如何在tensorflow2.0的keras模型中使用tf.train.ExponentialMovingAverage
【发布时间】:2019-12-07 01:48:08
【问题描述】:

我正在构建一个深度学习模型来进行一些分类,但我发现如果我使用随机裁剪,验证准确度会波动很大。我想使用短窗口的训练模型的运行平均值来帮助验证准确性,但我对它的使用感到很困惑。我正在使用 keras 的 inceptionv3 模型。

我用的是keras的inceptionv3模型,想用短窗口训练模型的运行平均值来帮助验证准确率。

ema = tf.train.ExponentialMovingAverage(0.99, step)
maintain_average = ema.apply()


model = tf.keras.applications.inception_v3.InceptionV3(include_top=True, weights=None, input_tensor=None, input_shape=None, pooling=None, classes=4)

def step_decay(epoch):
    initial_lrate = 0.045
    drop = 0.9
    epochs_drop = 2.0
    lrate = initial_lrate * math.pow(drop,  
           math.floor((epoch)/epochs_drop))
    return lrate

model.compile(loss='categorical_crossentropy',
              optimizer = tf.keras.optimizers.RMSprop(learning_rate=0.02, momentum=0.9, epsilon=0.1),
              metrics=['accuracy'])

checkpoint_cb = tf.keras.callbacks.ModelCheckpoint("classification_model_tf2.0_test.h5",                                          
                                                   save_best_only=True)
early_stopping_cb = tf.keras.callbacks.EarlyStopping(patience=10,                                  
                                                  restore_best_weights=True)

lrate = tf.keras.callbacks.LearningRateScheduler(step_decay)

history = model.fit_generator(
    data_generator(train_dataset),
    steps_per_epoch=train_steps_per_epoch,
    epochs=epochs,
    verbose=1,
    callbacks=[lrate, checkpoint_cb, early_stopping_cb],
    validation_data=data_generator(validation_dataset),
    validation_steps=vali_steps_per_epoch,
    workers = 0  # runs generator on the main thread
)

【问题讨论】:

    标签: tensorflow keras deep-learning computer-vision classification


    【解决方案1】:

    我认为,您可以使用 tfa.optimizers.MovingAverage 代替 tf.train.ExponentialMovingAverage https://www.tensorflow.org/addons/api_docs/python/tfa/optimizers/MovingAverage

    import tensorflow as tf
    import tensorflow_addons as tfa
    
    
    opt = tf.keras.optimizers.RMSprop(learning_rate=0.02, momentum=0.9, epsilon=0.1)
    opt = tfa.optimizers.MovingAverage(opt)
    model.compile(
        loss='categorical_crossentropy',
        optimizer=opt,
        metrics=['accuracy'])
    

    【讨论】:

    • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会失效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 2019-04-07
    • 2018-05-31
    • 1970-01-01
    相关资源
    最近更新 更多