我开始使用TensorFlow(从Caffe过来),并且正在使用损失函数。该函数接受标签,如0,1,...C-1,而不是onehot编码。现在,我想根据类别标签使用加权;如果我使用(one hot编码),则知道可以使用矩阵乘法来完成此操作。是否有任何方法可以在中实现相同的功能?
import tensorflow as tf
import numpy as np
np.random.seed(123)
sess = tf.InteractiveSession()
# let's say we have the logits and labels of a batch of size 6 with 5 classes
logits = tf.constant(np.random.randint(0, 10, 30).reshape(6, 5), dtype=tf.float32)
labels = tf.constant(np.random.randint(0, 5, 6), dtype=tf.int32)
# specify some class weightings
class_weights = tf.constant([0.3, 0.1, 0.2, 0.3, 0.1])
# specify the weights for each sample in the batch (without having to compute the onehot label matrix)
weights = tf.gather(class_weights, labels)
# compute the loss
tf.losses.sparse_softmax_cross_entropy(labels, logits, weights).eval()
weighted_cross_entropy_with_logits
的函数,可以计算加权softmax交叉熵。
SparseSoftmaxXentWithLogitsOp
是专门用于高效的非加权操作(底层使用SparseXentEigenImpl
),因此它不是“可插拔”的。tf.losses.sparse_softmax_cross_entropy
损失函数,正如先前已经建议的那样,在其中你将不得不根据当前批次中的标签传递权重。tf.contrib.losses.sparse_softmax_cross_entropy(logits, labels, weight=1.0, scope=None)
tf.nn.sparse_softmax_cross_entropy_with_logits.
权重作为损失函数的系数。如果提供了一个标量,则简单地将损失乘以给定的值。如果权重是大小为[batch_size]的张量,则损失权重适用于每个相应的样本。
tf.contrib.losses.sparse_softmax_cross_entropy
中的权重是每个样本的,而不是每个类别的。 - andong777