我正在使用TensorFlow训练一个模型,并希望在每个批次后打印模型的损失。我使用了一个自定义的训练循环,类似于以下代码:
import tensorflow as tffrom tensorflow.keras.losses import cosine_similarityfrom tensorflow.keras.optimizers import Adammodel = get_model(**model_params)g = get_generator(**generator_params)optimizer = Adam()epochs = 10for epoch in range(epochs): for i in range(len(g)): with tf.GradientTape() as tape: x,y = g[i] model_prediction = model(x) loss = cosine_similarity(y, model_prediction) gradients = tape.gradient(loss, model.trainable_weights) optimizer.apply_gradients(zip(gradients, model.trainable_weights)) print(f"Batch {i}/{len(g)}. Loss: {loss.eval(session=tf.Session()): .4f}")
由于损失是一个张量,为了能够看到其值,我需要将其转换为NumPy数组(计划并不是要打印数组,但一旦我能将张量转换为数组,就能解决我的问题)。不幸的是,我尝试的方法导致了以下错误:
Failed precondition: Error while reading resource variable dense_5/kernel from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist.`
我还尝试通过添加以下代码来编辑循环:
for epoch in range(epochs): for i in range(len(g)): with tf.GradientTape() as tape, tf.Session() as session: # 训练代码 loss_numpy = session.run(loss)
这会产生与上述相同的错误,我也尝试在每个训练步骤初始化全局变量:
for epoch in range(epochs): for i in range(len(g)): with tf.GradientTape() as tape, tf.Session() as session: # 训练代码 init = tf.global_variables_initializer() session.run(init) print(f"Batch {i}/{len(g)}. Loss: {session.run(loss): .4f}")
这不会抛出错误,但速度非常慢,并且输出许多我想避免的与Nvidia相关的其他信息。
有没有办法避免错误而无需在每个步骤进行变量初始化?或者是否有办法屏蔽与Nvidia相关的输出?
回答:
查看代码和错误,我的猜测是你没有正确处理TensorFlow会话和Keras所需和使用的范围。
一种可能是它没有被正确初始化。这是因为你没有使用照顾这些的标准Keras训练流程。或者它可能进行到一半,因为你使用了with
操作符,当with
内的块完成时,会话就被关闭了。这就是Python中with
的用途。
我自己没有尝试过,但我的直觉是,如果你在开始处理训练之前自己实例化一个会话,然后在整个过程中保持该会话,这应该可以工作。
顺便说一句,你实际上不需要将损失转换为NumPy对象来打印或检查它。如果你直接用TensorFlow进行数学运算,可能会在速度和稳定性方面更容易,并避免进行转换。