报告训练数据集中特定样本的训练损失,而不是训练过程中的平均损失 (TensorFlow)

Posted

技术标签:

【中文标题】报告训练数据集中特定样本的训练损失,而不是训练过程中的平均损失 (TensorFlow)【英文标题】:Report training loss for a specific sample in train dataset, not the average one in the training process (TensorFlow) 【发布时间】:2020-06-23 19:42:27 【问题描述】:

我正在使用 TensorFlow 训练 LSTM 模型。我们知道,在训练过程中,每个 epoch 的 lossval_loss 报告是训练和测试数据集损失的平均值。我打算跟踪火车数据集中特定样本的丢失(特定日期)。另外,应该注意的是,我在 fit 函数中洗牌训练数据。

【问题讨论】:

您可以创建一个特定的操作来计算该样本的损失,并在您需要损失值或将其放在摘要中时调用该操作。在纯 TensorFlow 的情况下,它将在会话运行中完成,而在 fit 函数(keras 方式)的情况下,您必须编写自定义回调。 @talos1904 您能否将其添加为答案并提供更多信息? 下面添加的代码 【参考方案1】:

这里是单个样本跟踪损失的代码:

import tensorflow as tf 
import numpy as np 
import keras 

x = tf.Variable(initial_value=np.ndarray(shape=(10, 10), dtype=np.float32)) # your sample input 
y =np.random.randint(0, 9, size=(10, )) # your sample label
y_labels = keras.utils.to_categorical(y, 10)

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=x, logits=y_labels)) # loss operation for that particular sample 
tf.summary.scalar('loss', loss) #logging loss op in summary 

print('loss op', loss)
merge = tf.summary.merge_all()
saver = tf.train.Saver()

with tf.Session() as sess: 
    sess.run(tf.global_variables_initializer())
    loss_val, merge_val = sess.run([loss, merge]) # no need to pass any feed_dict, loss value calculated is specific to that sample 
    print('loss val', loss_val)
    # merge val could be put in to tf summary writer 

【讨论】:

返回此错误:module 'tensorflow_core._api.v2.nn' has no attribute 'softmax_cross_entropy_with_logits_v2' 只是TensorFlow版本问题。我正在使用 1.13.2 版本来运行上述代码。

以上是关于报告训练数据集中特定样本的训练损失,而不是训练过程中的平均损失 (TensorFlow)的主要内容,如果未能解决你的问题,请参考以下文章

模型评价与损失函数

神经网络训练过程诊断

Bagging和Boosting

如何将数据集中的每 5 个样本分配为测试数据集,将其余样本分配为训练数据集?

在 SVM 中,支持向量可以不是训练样本吗?

交叉验证