python自定义交叉熵损失,再和pytorch api对比

背景

我们知道,交叉熵本质上是两个概率分布之间差异的度量,公式如下

其中概率分布P是基准,我们知道H(P,Q)>=0,那么H(P,Q)越小,说明Q约接近P。

损失函数本质上也是为了度量模型和完美模型的差异,因此可以用交叉熵作为损失函数,公式如下

其中

的部分不过是考虑到每次都是输入一批样本,因此把每个样本的交叉熵求出来以后要再求个平均。

注意,我的代码没有考虑标签是soft embedding的情况,如果遇到标注Y是\[0.1,0.1,0.8,0.1,0.8,0.1,0.1,0.1,0.8],那么你需要把代码再推广一下。

自定义交叉熵损失

python 复制代码
from typing import List
import math

def my_softmax(x:List[List[float]])->List[List[float]]:
    new_x:List[List[float]] = []
    for i in range(len(x)):
        sum:float = 0
        new_x_i = []
        for j in range(len(x[0])):
            sum += math.exp(x[i][j])
        for j in range(len(x[0])):
            new_x_i.append(math.exp(x[i][j])/sum)
        new_x.append(new_x_i)
    return new_x

def my_cross_entropy(x:List[List[float]],y:List[int])->float:
    res:float = 0
    x = my_softmax(x)
    for i in range(len(x)):
        res += -math.log(x[i][y[i]]) # 根号外面的1和底数e省去了
    res /= len(x) # mean
    return res

# 假设有一个简单的三分类问题,批量大小为2
# 预测输出(通常是模型的原始输出,没有经过softmax)
logits = [[1.5, 0.5, -0.5], [1.2, 0.2, 3.0]]
# 0 和 2 分别表示第一个和第三个类别是正确的
targets = [0, 2]
print(my_cross_entropy(logits,targets))

Pytorch交叉熵损失

python 复制代码
import torch
import torch.nn as nn

logits = torch.tensor([[1.5, 0.5, -0.5],
                       [1.2, 0.2, 3.0]])

targets = torch.tensor([0, 2])  

criterion = nn.CrossEntropyLoss()

loss = criterion(logits, targets)

print(loss.item())
相关推荐
FreakStudio16 小时前
W55MH32L-EVB 上手测评:硬件 TCP/IP 加持的以太网单片机,MicroPython 零门槛开发
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy·电子计算机
用户03321266636717 小时前
使用 Python 从零创建 Word 文档
python
Csvn1 天前
Python 两大经典坑点 —— 可变默认参数 & 闭包延迟绑定
后端·python
曲幽1 天前
别再用网页翻译看源码了!你的私人翻译神器LibreTranslate,部署避坑指南来了
python·docker·web·pot·translate·libretranslate·arogstranslate
用户556918817531 天前
#从脚本到独立程序:Python + Playwright 批量抓取的完整踩坑记录
python·自动化运维
兵慌码乱2 天前
基于 MediaPipe 与 PySide2 的手势交互音乐控制系统实现:轻量化视觉交互全流程解析
python·opencv·计算机视觉·人机交互·手势识别·mediapipe·pyside2
luckdewei2 天前
FastAPI 资产管理系统实战:复杂 ORM 关联、Alembic 迁移与 N+1 查询优化
python
aqi002 天前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn2 天前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python