python - 在 Keras 中调用 model.fit 时无法从损失函数运行打印语句
问题描述
我创建了一个名为的自定义损失函数
def customLoss(true, pred)
//do_stuff
//print(variables)
return loss
现在我调用编译为model.compile(optimizer='Adamax', loss = customLoss)
编辑:我尝试了 tf.Print,这是我的结果。
def customLoss(params):
def lossFunc(true, pred):
true = tf.Print(true, [true.shape],'loss-func') #obviously this won't work because the tensors aren't the same shape; however, this is what I want to do.
#stuff
return loss
return lossFunc
model = Model(inputs=[inputs], outputs=[outputs])
parallel_model = multi_gpu_model(model, gpus=8)
parallel_model.compile(opimizer='Adam', loss = customLoss(params), metrics = [mean_iou)
history = parallel_model.fit(X_train, Y_train, validation_split=0.25, batch_size = 32, verbose=1)
输出是
Epoch 1/10
1159/1159 [==============================] - 75s 65ms/step - loss: 0.1051 - mean_iou: 0.4942 - val_loss: 0.0924 - val_mean_iou: 0.6933
Epoch 2/10
1152/1159 [============================>.] - ETA: 0s - loss: 0.0408 - mean_iou: 0.7608
打印语句仍然没有打印。我错过了什么 - 我的输入tf.Print
不正确吗?
解决方案
这不是因为 Keras 转储缓冲区或做魔术,它根本不调用它们!损失函数被调用一次以构建计算图,然后返回代表损失值的符号张量。Tensorflow 使用它来计算损失、梯度等。
您可能会对tf.Print感兴趣,它是一个带有副作用的空操作,它打印传递的参数。由于tf.Print
它是计算图的一部分,因此它也将在训练时运行。从文档中:
打印张量列表。这是一个身份操作(行为类似于 tf.identity),在评估时具有打印数据的副作用。
推荐阅读
- javascript - 从文本字段附加值时,HTML 视频播放器不起作用
- android - 获取 Mesibo 连接状态 6 和 7
- c# - 如何为嵌套对象创建构建器
- graph - 如何存储和查询集合依赖问题
- javascript - 如何使用 useState React 钩子在子组件中更改父组件的值
- python - 如果第一个列表的最后一个元素是第二个的第一个,则合并两个列表
- srand - 尽管使用“srand”(gcc),但结果相同
- python - lambda函数中的异常处理?
- css - “没有 z-index 的堆叠”CSS 中的背景和边框大小写
- r - 从值列表中为 R 中的每一行填充值