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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • jquery获取jquery对象的html代码 OuterHtml

    jquery获取jquery对象的html代码 OuterHtml[code="java"]/***获取jquery的outerHtml*fromhttp://www.isharey.com/?p=1205*@param$domjquery对象*@returnstring*/functiongetJqueryOuterHtml($dom){return$($(”).html($dom.cl…

    2022年6月17日
    18
  • MySQL获取当前时间与日期间隔[通俗易懂]

    MySQL获取当前时间与日期间隔[通俗易懂]MySQL获取当前时间与日期间隔。MySQL常用的日期和时间函数:函数 说明 CURDATE()、CURRENT_DATE() 返回当前日期,格式:yyyy-MM-dd。 CURTIME()、CURRENT_TIME() 返回当前时间,格式:HH:mm:ss。 NOW()、CURRENT_TIMESTAMP()、LOCALTIME()、SYSDATE()、LO…

    2022年10月6日
    0
  • PhpStorm 2021.4.11 x64激活码【在线破解激活】

    PhpStorm 2021.4.11 x64激活码【在线破解激活】,https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月17日
    47
  • 使用fiddler对手机APP进行抓包

    使用fiddler对手机APP进行抓包在做手机或移动端APP的接口测试时,需要从开发人员那里获取接口文档,接口文档应该包括完整的功能接口、接口请求方式、接口请求URL、接口请求参数、接口返回参数。如果当前项目没有接口文档,则可以使用fiddler对APP进行抓包确认。在手机上对APP进行操作,然后在Fiddler中可以抓取对应的网络交互信息(一个功能中可能设计多个接口的交互)。在抓取的信息中可以看到接口请求方式、接口请求URL、接口请

    2022年5月16日
    82
  • HTTP 协议入门

    HTTP 协议入门

    2021年11月4日
    39
  • Oracle中MONTHS_BETWEEN函数的使用

    Oracle中MONTHS_BETWEEN函数的使用ORACLE中函数MONTHS_BETWEEN的使用 格式:MONTHS_BETWEEN(DATE1,DATE2)MONTHS_BETWEEN函数返回两个日期之间的月份数。SQL>selectmonths_between(to_date(‘20090228′,’yyyymmdd’),to_date(‘20080228′,’yyyymmdd’))asmonths…

    2022年7月12日
    19

发表回复

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

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