与Train complicated nn models with tf.eager (better with TF2 symbolic support)有轻微关系
我想用定制的训练过程训练一个网络。例如,我只想从当前最难的批处理样本中应用渐变。或者我想训练多个分担损失的模型。我想将列车过程分为向前通过、坡度的计算和坡度的应用,因为我不确定这些方法是否可以在通常的model.compile
->;model.fit
方法Keras
中使用。你知道吗
我不确定我是否会用手动的方式来做,也许有一种方法可以用model.compile
和model.fit
来处理渐变,但是我仍然对这个主题感兴趣。你知道吗
我想问以下问题
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())
目前没有回答
相关问题 更多 >
编程相关推荐