import torch from torch.nn import L1Loss, MSELoss from torch import nn # 1. 定义输入和目标(注意:需要 float32 类型) inputs = torch.tensor([1, 2, 3], dtype=torch.float32) targets = torch.tensor([1, 2, 5], dtype=torch.float32) # 2. reshape 成四维(batch, channel, height, width) inputs = torch.reshape(inputs, (1, 1, 1, 3)) targets = torch.reshape(targets, (1, 1, 1, 3)) # 3. L1Loss(平均绝对误差,默认 reduction='mean') loss_l1 = L1Loss() result_l1 = loss_l1(inputs, targets) print(f"L1Loss: {result_l1}") # tensor(0.6667) # 4. L1Loss + reduction='sum' loss_l1_sum = L1Loss(reduction='sum') result_l1_sum = loss_l1_sum(inputs, targets) print(f"L1Loss (sum): {result_l1_sum}") # tensor(2.) # 5. MSELoss(均方误差) loss_mse = MSELoss() result_mse = loss_mse(inputs, targets) print(f"MSELoss: {result_mse}") # tensor(1.3333) # 6. CrossEntropyLoss(交叉熵,常用于分类) x = torch.tensor([0.1, 0.2, 0.3]) y = torch.tensor([1]) # 真实类别索引为 1 x = torch.reshape(x, (1, 3)) loss_cross = nn.CrossEntropyLoss() result_cross = loss_cross(x, y) print(f"CrossEntropyLoss: {result_cross}") # tensor(1.1019)1.inputs = torch.tensor([1, 2, 3], dtype=torch.float32):创建一个浮点型张量
2.inputs = torch.reshape(inputs, (1, 1, 1, 3))
targets = torch.reshape(targets, (1, 1, 1, 3))
把输入张量和目标张量用reshape搞成形状一致,因为后面的loss函数里需要同类型的参数
这里的(1, 1, 1, 3))分别是1张图片,一个通道,高1像素,宽3像素
3.L1Loss:平均绝对误差
L1Loss = mean(|预测值 - 真实值|)
计算过程:
| 位置 | 预测值 | 真实值 | 绝对误差 |
|---|---|---|---|
| 第1个 | 1 | 1 | |1-1| = 0 |
| 第2个 | 2 | 2 | |2-2| = 0 |
| 第3个 | 3 | 5 | |3-5| = 2 |
平均绝对误差 = (0 + 0 + 2) / 3 = 0.6667
4.L1Loss(reduction='sum'):把平均绝对误差再求和
此题就是0.6667*3=2
5. MSELoss(均方误差):先求每个位置的误差平方,再求平均值
计算过程
| 位置 | 预测值 | 真实值 | 误差(预测-真实) | 误差的平方 |
|---|---|---|---|---|
| 第1个 | 1 | 1 | 0 | 0² = 0 |
| 第2个 | 2 | 2 | 0 | 0² = 0 |
| 第3个 | 3 | 5 | -2 | (-2)² = 4 |
均方误差 = (0 + 0 + 4) / 3 = 1.3333
6.CrossEntropyLoss(交叉熵,常用于分类)
x = torch.tensor([0.1, 0.2, 0.3])是神经网络给出的三个图片的得分,得分越高代表越像,目前
[0.1, 0.2, 0.3]表示0,1,2三类中2分数最高是0.3
y = torch.tensor([1]) #真实图片是1类的
x = torch.reshape(x, (1, 3)),原来x是一维的,CrossEntropyLoss需要二维的数,所以用reshape改成一行两列的二维数
如何计算CrossEntropyLoss,这题为例:
第 1 步:把分数变成概率
模型打的分是0.1, 0.2, 0.3,但损失函数要的是概率(加起来等于 1)。所以先把分数转成概率,用的是Softmax。
转换方法:每个分数取 e 的次方,然后除以总和。
e^0.1 = 1.105 e^0.2 = 1.221 e^0.3 = 1.350 总和 = 1.105 + 1.221 + 1.350 = 3.676
概率:
类别 0: 1.105 / 3.676 = 0.3006 类别 1: 1.221 / 3.676 = 0.3322 ← 正确答案的概率 类别 2: 1.350 / 3.676 = 0.3672
第 2 步:看正确答案的概率
正确答案是类别 1,概率是0.3322。
第 3 步:算损失
损失公式:-log(正确答案的概率)
-log(0.3322) = 1.1019