python - TensorFlow 中的自定义损失函数用于对训练数据进行加权

标签 python machine-learning tensorflow

我想根据训练数据集中的列对训练数据进行加权。因此,某些培训项目比其他培训项目更加重要。加权列不应作为输入层的特征包含在内。

Tensorflow 文档包含 example如何使用项目的标签来分配自定义损失,从而分配权重:

# Ensures that the loss for examples whose ground truth class is `3` is 5x
# higher than the loss for all other examples.
weight = tf.multiply(4, tf.cast(tf.equal(labels, 3), tf.float32)) + 1

onehot_labels = tf.one_hot(labels, num_classes=5)
tf.contrib.losses.softmax_cross_entropy(logits, onehot_labels, weight=weight)

我在具有三个隐藏层的自定义DNN中使用它。理论上,我只需要将上面示例中的标签替换为包含权重列的张量即可。

我知道有几个线程已经讨论了类似的问题,例如defined loss function in tensorflow?

出于某种原因,我在尝试引入体重列时遇到了很多问题。这可能是两行简单的代码,或者可能有一种更简单的方法来实现相同的结果。

最佳答案

我相信我找到了答案:

  weight_tf = tf.range(features.get_shape()[0]-1, features.get_shape()[0])
  loss = tf.losses.softmax_cross_entropy(target, logits, weights=weight_tf)

权重是特征 tensorflow 中的最后一列。

关于python - TensorFlow 中的自定义损失函数用于对训练数据进行加权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43409488/

相关文章:

machine-learning - Keras 可以处理不同尺寸的输入图像吗?

machine-learning - 异常: The passed model is not callable and cannot be analyzed directly with the given masker

machine-learning - 这是过度拟合吗?

tensorflow - 如何使用tensorflow对象检测API进行人脸检测

python - 类型错误 : only integer scalar arrays can be converted to a scalar index

python - 如何使用 GitPython 库 git pull rebase?

python - python中的单词n-gram句子列表

python - Django FilePathField 不适用于相对路径

tensorflow - 为什么 Tensorflow 将 int32/int32 转换为 float64 以及如何阻止它?

python - 自动完成不起作用 : emacs elpy-mode