交叉熵损失函数计算过程(tensorflow)

交叉熵损失函数通常用于多类分类损失函数计算。计算公式如下:
在这里插入图片描述
P为真实值,Q为预测值。

使用tensorflow计算

import tensorflow as tf
import keras

# 创建一个示例数据集
# 假设有3个样本,每个样本有4个特征,共2个类别
# 目标标签为稀疏表示(每个样本的类别用类别索引表示)
y_true = tf.constant([0, 1, 1])  # 真实标签
y_pred = tf.constant([[0.9, 0.1], [0.2, 0.8], [0.3, 0.7]])  # 模型预测

# 使用SparseCategoricalCrossentropy计算损失
loss_fn = keras.losses.SparseCategoricalCrossentropy()
loss = loss_fn(y_true, y_pred)
print("损失值:", loss.numpy())
# 损失值: 0.22839303

手动计算

真实标签:[0,1,1]写成one-hot形式 [[1,0],[0,1],[0,1]]
预测标签(经过softmax):[[0.9, 0.1], [0.2, 0.8], [0.3, 0.7]]

import math

h1 = (1 * math.log(0.9) + 0 * math.log(0.1))
h2 = (0 * math.log(0.2) + 1 * math.log(0.8))
h3 = (0 * math.log(0.3) + 1 * math.log(0.7))
h = -(h1 + h2 + h3) / 3
print("损失值:", h)
# 损失值: 0.22839300363692283

注意多标签分类和多类分类区别与联系。

参考

  • 9
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
TensorFlow中,交叉熵损失函数常用于图像分类问题。具体而言,有三个函数可以用于计算交叉熵损失:tf.nn.softmax_cross_entropy_with_logits、tf.nn.softmax_cross_entropy_with_logits_v2和tf.nn.sparse_softmax_cross_entropy_with_logits。 举个例子,如果你的标签是稀疏的,可以使用tf.nn.sparse_softmax_cross_entropy_with_logits函数,并确保正确设置labels参数的维度。而对于其他复杂情况,可以使用tf.nn.softmax_cross_entropy_with_logits_v2函数。 值得注意的是,在实际应用中,你可能需要使用更高级的技巧,如为不平衡的类别赋予不同的损失权重,以及使用不同的参数和技术来调整模型以获得更好的性能。这些高级技巧可以根据具体的问题和数据集进行调整和优化。 总结起来,通过使用TensorFlow中的不同交叉熵损失函数,你可以在图像分类问题中计算出有效的损失,并根据需要进行进一步的优化和调整。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [tensorflow交叉熵损失函数](https://blog.csdn.net/wangs0622/article/details/90668729)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [交叉熵损失函数-使用 Tensorflow 库在 Python 中实现交叉熵损失函数的示例](https://download.csdn.net/download/m0_64919777/87401829)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值