python复现softmax损失函数详细版

python复现softmax损失函数详细版fromtorchimportnnimporttorchdefloss_func(output,target):one_hot=torch.zeros_like(output)foriinrange(target.size(0)):one_hot[i,target[i]]=1softmax_out=torch.exp(output)/(torch.unsque…

大家好,又见面了,我是你们的朋友全栈君。

主要内容

  • softmax和交叉熵公式
  • 单个样本求解损失
  • 多个样本求解损失

softmax和交叉熵公式

  • softmax

先来看公式,softmax的作用是将样本对应的输出向量,转换成对应的类别概率值。这里使用以e为底的指数函数,将向量值归一化为0-1的概率值;
Alt
使用numpy的代码实现也很简单,但是当数值过大时会发生溢出,此时会将向量中的其他值减去最大值,数值平移到0附近。会避免溢出现象。ps:这里暂时不考虑这种情况
在这里插入图片描述

  • softmax交叉熵
    交叉熵是用来衡量分布p和q之间的相似度,越相似交叉熵越小。其中 p ( x ) p(x) p(x)是真实标签的one_hot编码, q ( x ) q(x) q(x)是预测值。需要注意的是这里的 q ( x ) q(x) q(x)必须是经过softmax的概率值。
    Alt

单个样本求解损失

#conding=utf-8

from torch import nn
import torch
import numpy as np

def MySoftmax(vector):
    return np.exp(vector)/np.exp(vector).sum()

def LossFunc(target,output):
    output = MySoftmax(output)
    one_hot = np.zeros_like(output)
    one_hot[:,target] = 1
    # print(one_hot)
    loss = (-np.log(output)*one_hot).sum()
    return loss
target = np.array([1])
output = np.array([[8,-3.,10]])
softmax_out = MySoftmax(output)
np.set_printoptions(suppress=True)
print(softmax_out)

# torch自带的softmax实现
print(nn.Softmax()(torch.Tensor(output)))

print(LossFunc(target,output))
print(nn.CrossEntropyLoss(reduction="sum")(torch.Tensor(output),torch.Tensor(target).long()))

需要注意的是现有的框架中基本都会在损失函数内部进行softmax转换。我这里设置的loss值没有求平均,所以reduction=“sum”

多个样本求解损失

#conding=utf-8

from torch import nn
import torch
import numpy as np

# def MySoftmax(vector):
# return np.exp(vector)/np.exp(vector).sum()
#
# def LossFunc(target,output):
# output = MySoftmax(output)
# one_hot = np.zeros_like(output)
# one_hot[:,target] = 1
# # print(one_hot)
# loss = (-np.log(output)*one_hot).sum()
# return loss
# target = np.array([1])
# output = np.array([[8,-3.,10]])
# softmax_out = MySoftmax(output)
# np.set_printoptions(suppress=True)
# print(softmax_out)
#
# # torch自带的softmax实现
# print(nn.Softmax()(torch.Tensor(output)))
#
# print(LossFunc(target,output))
# print(nn.CrossEntropyLoss(reduction="sum")(torch.Tensor(output),torch.Tensor(target).long()))

def loss_func(output,target):
    one_hot = torch.zeros_like(output)
    for i in range(target.size(0)):
        one_hot[i,target[i]]=1

    softmax_out = torch.exp(output)/( torch.unsqueeze(torch.exp(output).sum(dim=1),dim=1))
    # 确保每一个样本维度的概率之和为1
    print(softmax_out.sum(dim=1))
    loss = (-torch.log(softmax_out) * one_hot).sum()
    return loss

target = torch.Tensor([1,1,1]).long()
output = torch.Tensor([[10.,-5,5],[5,2,-1],[4,-9,5]])
softmax = nn.Softmax(dim=1)


criterion = nn.CrossEntropyLoss(reduction="sum")
print(criterion(output,target))
print(loss_func(output,target))

我这里使用的是torch的计算,主要原因是想使用label smoothing技巧,torch版在项目中应用更方便。
只是将numpy换成torch的形式,基本的公式都没有改变的。需要注意的是在多个样本求解softmax值是在样本的维度求概率。

喜欢的童鞋点个赞哦!大家有什么要了解的请留言,老汤尽量满足

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/153145.html原文链接:https://javaforall.net

(0)
上一篇 2022年6月26日 下午4:16
下一篇 2022年6月26日 下午4:16


相关推荐

  • LoopBox 用于包装循环的盒子

    LoopBox 用于包装循环的盒子LoopBox 用于包装循环的盒子

    2022年4月22日
    57
  • 因果图法用例设计

    因果图法用例设计等价类划分法和边界值法着重考虑输入条件 而不考虑输入条件的组合 决策表考虑了输入条件的组合情况 但没有考虑输入条件之间的相互制约的关系 在查看程序规格说明时 如果发现输入之间有关系 相应会产生多个动作 需要考虑条件组合的情况 又发现条件之间存在相互制约 可以考虑使用因果图法 因果图法概述 1 因果图法相关概念因果图法是一种适合于描述对于多种条件的组合 相应产生多个动作的形式的方法 对照规格说明书利用图解法分析输入条件的组合 约束关系和输出条件的因果关系 从而设计测试用例的方法 它适合于检查程

    2026年3月18日
    2
  • Axure 8 亲测可用授权码

    Axure 8 亲测可用授权码被授权人 zdfans com 授权密钥 gP5uuK2gH iIVO3YFZwoKy FF3pAz7dTu8B

    2026年3月19日
    3
  • 深化战略合作,优刻得接入智谱最强开源多模态GLM-4.5V

    深化战略合作,优刻得接入智谱最强开源多模态GLM-4.5V

    2026年3月12日
    4
  • web聊天框页面

    web聊天框页面DOCTYPE tml htmllang en head metacharset UTF 8 title 聊天窗口 title metaname renderer content webkit metahttp equiv X UA Compatible content IE edge chrome 1 amp l metahttp equiv X UA Compatible content IE edge chrome 1 metaname renderer content webkit metacharset UTF 8 head htmllang en

    2025年11月17日
    6
  • 模拟退火 python_粒子群算法怎么设置约束条件

    模拟退火 python_粒子群算法怎么设置约束条件1、最优化与线性规划最优化问题的三要素是决策变量、目标函数和约束条件。线性规划(Linearprogramming),是研究线性约束条件下线性目标函数的极值问题的优化方法,常用于解决利用现有的资源得到最优决策的问题。简单的线性规划问题可以用Lingo软件求解,Matlab、Python中也有求解线性规划问题的库函数或求解器,很容易学习和使用,并不需要用模拟退火算法。但是,由一般线性规划问题所衍生的整数规划、混合规划、0/1规划、二次规划、非线性规划、组合优化问题,则并不是调用某个库函数都能处理.

    2022年10月13日
    4

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号