我试图将权重引入以下成本函数:
_cost = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=_logits, labels=y))
但不必自己做 softmax 交叉熵。因此,我正在考虑将成本计算分解为 cost1 和 cost2,并为每个成本提供 logits 和 y 值的修改版本。
我想做这样的事情,但不确定正确的代码是什么:
mask=(y==0)
y0 = tf.boolean_mask(y,mask)*y1Weight
(这给出了掩码不能是标量的错误)
权重掩模可以使用以下方式计算tf.where
。这是加权成本示例:
batch_size = 100
y1Weight = 0.25
y0Weight = 0.75
_logits = tf.Variable(tf.random_normal(shape=(batch_size, 2), stddev=1.))
y = tf.random_uniform(shape=(batch_size,), maxval=2, dtype=tf.int32)
_cost = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=_logits, labels=y)
#Weight mask, the weights for label=0 is y0Weight and for 1 is y1Weight
y_w = tf.where(tf.cast(y, tf.bool), tf.ones((batch_size,))*y0Weight, tf.ones((batch_size,))*y1Weight)
# New weighted cost
cost_w = tf.reduce_mean(tf.multiply(_cost, y_w))
正如@user1761806所建议的,更简单的解决方案是使用tf.losses.sparse_softmax_cross_entropy()
它允许对类别进行加权。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)