gpt4 book ai didi

python - 如何使用 sparse_softmax_cross_entropy_with_logits 在 tensorflow 中实现加权交叉熵损失

转载 作者:太空狗 更新时间:2023-10-29 18:18:30 36 4
gpt4 key购买 nike

我开始使用 tensorflow(来自 Caffe),我正在使用损失 sparse_softmax_cross_entropy_with_logits。该函数接受像 0,1,...C-1 这样的标签,而不是 onehot 编码。现在,我想根据类标签使用权重;我知道,如果我使用 softmax_cross_entropy_with_logits(一个热编码),这可能可以通过矩阵乘法来完成,有没有办法用 sparse_softmax_cross_entropy_with_logits 做同样的事情?

最佳答案

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()

关于python - 如何使用 sparse_softmax_cross_entropy_with_logits 在 tensorflow 中实现加权交叉熵损失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40198364/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com