gpt4 book ai didi

python - 加权分类交叉熵语义分割

转载 作者:行者123 更新时间:2023-12-04 15:57:15 24 4
gpt4 key购买 nike

我想使用 FCN(一种 U-Net)来进行一些语义分割。我使用基于 Tensorflow 后端的 Python 和 Keras 执行它。现在我有了很好的结果,我正在努力改进它们,我认为做这样的事情的一种方法是改进我的损失计算。我知道在我的输出中,几个类是不平衡的,使用默认的 categorical_crossentropy 函数可能会出现问题。我的模型输入和输出都是 float32 格式,输入是 channel_first,输出和 channel_last(排列在模型末尾完成)在二进制情况下,当我只想分割一个类时,我以这种方式更改了损失函数,以便它可以根据输出内容逐个添加权重:

def weighted_loss(y_true, y_pred):
def weighted_binary_cross_entropy(y_true, y_pred):
w = tf.reduce_sum(y_true)/tf_cast(tf_size(y_true), tf_float32)
real_th = 0.5-th
tf_th = tf.fill(tf.shape(y_pred), real_th)
tf_zeros = tf.fill(tf.shape(y_pred), 0.)
return (1.0 - w) * y_true * - tf.log(tf.maximum(tf.zeros, tf.sigmoid(y_pred) + tf_th)) +
(1- y_true) * w * -tf.log(1 - tf.maximum(tf_zeros, tf.sigmoid(y_pred) + tf_th))
return weighted_binary_coss_entropy

请注意,th 是激活阈值,默认情况下为 1/nClasses,我已对其进行更改以查看什么值能给我最好的结果你怎么看待这件事?如何更改它以便它能够计算加权分类交叉熵(在多类的情况下)

最佳答案

您的实现将适用于二进制类,对于多类它只是

  -y_true * tf.log(tf.sigmoid(y_pred)) 

并使用内置的 tensorflow 方法计算分类熵,因为它避免了 y_pred<0

的溢出

你可以查看这个答案 Unbalanced data and weighted cross entropy,它解释了加权分类交叉熵的实现。

categorical_crossentropy 的唯一变化是

def weighted_loss(y_true, y_pred):
def weighted_categorical_cross_entropy(y_true, y_pred):
w = tf.reduce_sum(y_true)/tf_cast(tf_size(y_true), tf_float32)
loss = w * tf.nn.softmax_cross_entropy_with_logits(onehot_labels, logits)
return loss
return weighted_categorical_cross_entropy

为单个类别提取预测

def loss(y_true, y_pred):
s = tf.shape(y_true)

# if number of output classes is at last
number_classses = s[-1]

# this will give you one hot code for your prediction
clf_pred = tf.one_hot(tf.argmax(y_pred, axis=-1), depth=number_classses, axis=-1)

# extract the values of y_pred where y_pred is max among the classes
prediction = tf.where(tf.equal(clf_pred, 1), y_pred, tf.zeros_like(y_pred))

# if one hotcode == 1 then class1_prediction == y_pred else class1_prediction ==0
class1_prediction = prediction[:, :, :, 0:1]
# you can compute your loss here on individual class and return the loss ,just for simplicity i am returning the class1_prediction
return class1_prediction

模型输出

y_pred = [[[[0.5, 0.3, 0.7],
[0.6, 0.3, 0.2]]
,
[[0.7, 0.9, 0.6],
[0.3 ,0.9, 0.3]]]]

相应的基本事实

y_true =  [[[[0,  1, 0],
[1 ,0, 0]]
,
[[1,0 , 0],
[0,1, 0]]]]

第 1 类的预测

prediction = loss(y_true, y_pred)
# prediction = [[[[0. ],[0.6]],[0. ],[0. ]]]]

关于python - 加权分类交叉熵语义分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51361402/

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