损失函数的学习笔记

损失函数的学习笔记:

本文为初学者学习笔记,仅作记录用,如有错误还请指正。

一、损失函数的定义

损失函数(loss function)就是用来度量模型的预测值f(x)与真实值Y的差异程度的运算函数,它是一个非负实值函数,通常使用L(Y, f(x))来表示。

即,用通俗的话来说,损失函数就是度量模型准确程度的一个函数

二、损失函数的分类

损失函数的计算公式大致有以下两类:

二、1.回归问题损失函数

(1)绝对值损失函数/曼哈顿距离/L1损失函数

即计算每个预测值和与其对应的真实值的差的绝对值之和,所得值即为loss值。
数学公式为:


(该公式未添加真实值权重)
在这里插入图片描述
(该公式添加了真实值权重,可以自己调整数值)

(2)平方损失函数
在这里插入图片描述

二、2 分类问题损失函数

此处仅列举0-1损失函数和交叉熵损失函数
(1) 0-1损失函数

在这里插入图片描述

(2)交叉熵损失函数(可用于概率

在这里插入图片描述

三、代码实现

三、1. L1loss函数

import torch as th
import torch.nn as nn

loss = nn.L1Loss(reduction='sum')
a = th.tensor([1, 0, 1, 2])
b = th.tensor([1, 1, 0, 1])

loss_1 = loss(a, b)
print(loss_1)

三、2. 平方损失函数

import torch as th
import torch.nn as nn

loss = nn.MSELoss(reduction='sum')
a = th.tensor([1, 0, 1, 3], dtype=float)
b = th.tensor([1, 1, 0, 1])

loss_1 = loss(a, b)
print(loss_1)

(此处输出结果为6.,不知解决方法)

三、3. 0-1损失函数

import torch as th


def zero_one(y, y_predict):
    i = 0
    c = 0
    while c < len(y):
        if y[c] == y_predict[c]:
            i += 1
            c += 1
        else:
            i += 0
            c += 1
    return i


a = th.tensor([2, 1])
b = th.tensor([2, 3])
zero_one_loss = zero_one(a, b)
print(zero_one_loss)

三、4. 交叉熵函数

def CCE (y, y_predicted):
cce_class = y * (np.log(y_predicted))
sum_totalpair_cce = np.sum(cce_class)
cce = - sum_totalpair_cce / y.size
return cce

四、参考

http://t.csdn.cn/1b9n1
http://t.csdn.cn/xwNxV
https://zhuanlan.zhihu.com/p/261059231
https://www.bilibili.com/video/BV1vg411172u/?spm_id_from=333.337.search-card.all.click&vd_source=74d7a702ad725d97e7f890100ec2b664

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值