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())
相关推荐
___波子 Pro Max.8 分钟前
GitHub Actions配置python flake8和black
python·black·flake8
阿蒙Amon1 小时前
【Python小工具】使用 OpenCV 获取视频时长的详细指南
python·opencv·音视频
橘子编程2 小时前
Python-Word文档、PPT、PDF以及Pillow处理图像详解
开发语言·python
蓝婷儿2 小时前
Python 机器学习核心入门与实战进阶 Day 2 - KNN(K-近邻算法)分类实战与调参
python·机器学习·近邻算法
之歆3 小时前
Python-封装和解构-set及操作-字典及操作-解析式生成器-内建函数迭代器-学习笔记
笔记·python·学习
天天爱吃肉82183 小时前
ZigBee通信技术全解析:从协议栈到底层实现,全方位解读物联网核心无线技术
python·嵌入式硬件·物联网·servlet
Allen_LVyingbo4 小时前
Python常用医疗AI库以及案例解析(2025年版、上)
开发语言·人工智能·python·学习·健康医疗
智能砖头4 小时前
LangChain 与 LlamaIndex 深度对比与选型指南
人工智能·python
风逸hhh6 小时前
python打卡day58@浙大疏锦行
开发语言·python
盼小辉丶6 小时前
PyTorch实战(14)——条件生成对抗网络(conditional GAN,cGAN)
人工智能·pytorch·生成对抗网络