TF+eager+Keras中的人工权重正则化

2024-03-28 22:51:04 发布

您现在位置:Python中文网/ 问答频道 /正文

Train complicated nn models with tf.eager (better with TF2 symbolic support)有轻微关系

我想用定制的训练过程训练一个网络。例如,我只想从当前最难的批处理样本中应用渐变。或者我想训练多个分担损失的模型。我想将列车过程分为向前通过、坡度的计算和坡度的应用,因为我不确定这些方法是否可以在通常的model.compile->;model.fit方法Keras中使用。你知道吗

我不确定我是否会用手动的方式来做,也许有一种方法可以用model.compilemodel.fit来处理渐变,但是我仍然对这个主题感兴趣。你知道吗

我想问以下问题

  1. 下面的代码是否正确计算正则化损失的梯度?你知道吗
def loss_fun(model, image_batch, label_batch, reg_loss_coef=1e-5):
    main_loss = my_another_loss_fun(image_batch, label_batch)

    reg_sum = 1e-5
    for layer in model.layer:
        is_trainable = layer.trainable

        is_weight = is_trainable and (type(layer) == tf.keras.layers.Conv2D) #model-dependent check here
        if is_weight:
            for var in layer.variables:
                reg_sum += tf.math.reduce_sum(tf.math.square(var)) * reg_loss_coef

    return main_loss + reg_sum

model = tf.keras.applications.inception_resnet_v2.InceptionResNetV2(weights=None)
opt = tf.train.AdamOptimizer(0.01, epsilon=1e-5)    
ds_tf = tf.data.Dataset.something()
for im_b, label_b in ds_tf:
    with tf.GradientTape() as tape:
        curr_loss = loss_fun(model, im_b, label_b)
        with tape.stop_recording():
            grads = tape.gradient(curr_loss, model.trainable_variables)
            opt.apply_gradients(zip(grads, model_vars),
                        global_step=tf.train.get_or_create_global_step())
  1. 我能检查梯度计算吗(特别是正则化梯度)?你知道吗

Tags: 方法layerformodelistfwithbatch