tensorflow - 如何在 tensorflow2.0 的 keras 模型中使用 tf.train.ExponentialMovingAverage

标签 tensorflow keras deep-learning computer-vision classification

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

最佳答案

我认为,您可以使用 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'])

关于tensorflow - 如何在 tensorflow2.0 的 keras 模型中使用 tf.train.ExponentialMovingAverage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57258604/

相关文章:

python - 在 resnet 模型中拟合图像时出现尺寸问题

matlab - 是否可以绘制混淆矩阵的子图?

python - 导入自己的数据,例如 MNIST 或 CIFAR10 load_data()

python - 使用文件夹结构在 Keras 中进行预测时如何获得正确的标签?

python - 将 tf.Tensor 转换为 numpy 数组,然后将其另存为图像而不需要eager_execution

python - Keras的evaluate_generator准确率高,但各个类别的准确率较低

python - 用于 DQN 强化学习的 Keras Tensorboard

python - 具有 tf.contrib.losses.metric_learning.triplet_semihard_loss 断言错误的 keras 模型

deep-learning - 如何在 Keras 中使用 return_sequences 选项和 TimeDistributed 层?

python - Tensorboard 图像摘要