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())
相关推荐
曲幽4 小时前
FastAPI + PostgreSQL 实战:从入门到不踩坑,一次讲透
python·sql·postgresql·fastapi·web·postgres·db·asyncpg
用户8356290780518 小时前
使用 C# 在 Excel 中创建数据透视表
后端·python
码路飞11 小时前
FastMCP 实战:一个 .py 文件,给 Claude Code 装上 3 个超实用工具
python·ai编程·mcp
dev派13 小时前
AI Agent 系统中的常用 Workflow 模式(2) Evaluator-Optimizer模式
python·langchain
前端付豪15 小时前
AI 数学辅导老师项目构想和初始化
前端·后端·python
用户03321266636715 小时前
将 PDF 文档转换为图片【Python 教程】
python
悟空爬虫17 小时前
UV实战教程,我啥要从Anaconda切换到uv来管理包?
python
dev派17 小时前
AI Agent 系统中的常用 Workflow 模式(1)
python·langchain
明月_清风19 小时前
从“能用”到“专业”:构建生产级装饰器与三层逻辑拆解
后端·python
曲幽1 天前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic