具有阶段的Tensorflow自定义培训

时间:2019-09-19 13:24:57

标签: python tensorflow keras deep-learning dropout

我需要使用Tensorflow / Keras创建一个自定义训练循环(因为我想拥有多个优化器,并告诉每个优化器应该作用于哪些权重)。

尽管this tutorialthat one too在这件事上很清楚,但他们错过了一个非常重要的要点:我如何预测训练阶段以及如何预测验证相?

假设我的模型有Dropout层或BatchNormalization层。无论是培训还是验证,他们的工作方式肯定完全不同。

如何修改这些教程?这是一个虚拟示例(可能包含一两个伪代码):

# Iterate over epochs.
for epoch in range(3):


    # Iterate over the batches of the dataset.
    for step, (x_batch_train, y_batch_train) in enumerate(train_dataset):
        with tf.GradientTape() as tape:

            #model with two outputs
            #IMPORTANT: must be in training phase (use dropouts, calculate batch statistics)
            logits1, logits2 = model(x_batch_train) #must be "training"

            loss_value1 = loss_fn1(y_batch_train[0], logits1)
            loss_value2 = loss_fn2(y_batch_train[1], logits2)

            grads1 = tape.gradient(loss_value1, model.trainable_weights[selection1])    
            grads2 = tape.gradient(loss_value2, model.trainable_weights[selection2])

            optimizer1.apply_gradients(zip(grads1, model.trainable_weights[selection1]))
            optimizer2.apply_gradients(zip(grads2, model.trainable_weights[selection2]))



    # Run a validation loop at the end of each epoch.
    for x_batch_val, y_batch_val in val_dataset:

        ##Important: must be validation phase
            #dropouts are off: calculate all neurons and divide value    
            #batch norms use previously calculated statistics    
        val_logits1, val_logits2 = model(x_batch_val)

        #.... do the evaluations

1 个答案:

答案 0 :(得分:2)

我认为您可以在调用tf.keras.Model时传递一个training参数,并将其向下传递到各层:

# On training
logits1, logits2 = model(x_batch_train, training=True)
# On evaluation
val_logits1, val_logits2 = model(x_batch_val, training=False)