【Tensorflow】【损失函数】交叉熵数据验证(下)---BinaryCrossentropy二分类

every blog every motto: You can do more than you think.

0. 前言

对交叉熵的具体过程用数据进行验证
说明: 关于交叉熵的基本概念和多分类交叉熵数据验证,参考上篇多分类交叉熵CategoricalCrossentropy

1. 正文

1.1 BinaryCrossentropy公式

l o s s = − 1 o u t p u t s i z e ∑ i = 1 o u t p u t s i z e [ y i × l o g y i ^ + ( 1 − y i ) × l o g ( 1 − y i ^ ) ] loss = -\frac{1}{output size}\sum_{i=1}^{output size}[y_i \times log\hat{y_i}+(1-y_i) \times log(1-\hat{y_i})] loss=outputsize1i=1outputsize[yi×logyi^+(1yi)×log(1yi^)]

说明:

  • yi: 是真实值
  • y_hat: 预测值
  • output size: 图片的 “像素值” 的个数,如:图片shape: (batch,height,width,channel) , 那就是他们4个数的乘积。

1.2 数据验证

import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
from tensorflow.keras.losses import BinaryCrossentropy
import numpy as np

loss = BinaryCrossentropy()

1.2.1 一维

# 一维
y_true = np.array([0, 1, 1])
y_pred = np.array([0.6, 0.4, 0.3])
  1. tf
loss_result_1 = loss(y_true, y_pred)
print('交叉熵计算:', loss_result_1)

在这里插入图片描述
2. numpy

np_result_1 = y_true * np.log(y_pred) + (1 - y_true) * np.log(1 - y_pred)
np_result_1 = -np.sum(np_result_1)/y_true.size
print('numpy计算:', np_result_1)
  1. 单个元素计算
    每个对应的值进行计算
    在这里插入图片描述
# 3. 单个元素计算
temp = -(1*np.log(0.4)+1*np.log(0.4)+1*np.log(0.3))/3
print('单个元素计算:', temp)

在这里插入图片描述

1.2.2 二维

y_true = np.array([[0, 1], [0, 0]])
y_pred = np.array([[0.2, 0.9], [0.1, 0.2]])
  1. tf
loss_result_1 = loss(y_true, y_pred)
print('交叉熵计算:', loss_result_1)

在这里插入图片描述

  1. numpy
np_result_1 = y_true * np.log(y_pred) + (1 - y_true) * np.log(1 - y_pred)
np_result_1 = -np.sum(np_result_1) / y_true.size
print('numpy计算:', np_result_1)

在这里插入图片描述
3. 单个元素计算

temp = -(1 * np.log(0.8) + 1 * np.log(0.9) + 1 * np.log(0.9)+ 1 * np.log(0.8)) / 4
print('单个元素计算:', temp)

在这里插入图片描述

1.2.3 小结

以图片分割为例:
图片shape: (batch,height,width,channel)

  • 上篇文章中Crossentropy是对通道方向上进行计算,损失=总和/(batch+height+width)。
  • 本文的BinaryCrossentropy对每个值进行计算,损失=总和/(batch+height+width+channel
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

胡侃有料

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值