问题
In my project, the negative instance is far more than positive instance, so I want to give positive instance with a larger weight. my target is:
loss = 0.0
if y_label==1:loss += 100 * cross_entropy
else:loss += cross_entropy
How to realizate this in tensorflow[?]
回答1:
Let losses
to be a vector (rank-1 tensor) of loss values for the examples in your batch. And let y
be the the vector of corresponding labels. You could then achieve the result you want by
weights = w_pos*y + w_neg*(1.0-y)
loss = tf.reduce_mean(weights*losses)
Here, w_pos
and w_neg
are constant scalar values (w_pos=100.0
and w_neg=1.0
in your example). The vector weights
then has a value of w_pos
for examples where the label equals 1 and w_neg
where it equals 0. You then multiply weights
element-wise with losses
to weigh the values in the losses
according to the corresponding labels and then take the mean.
来源:https://stackoverflow.com/questions/43273677/defined-loss-function-in-tensorflow