defined loss function in tensorflow?

陌路散爱 提交于 2019-12-11 04:51:55

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!