import torch from torch.nn import L1Loss, MSELoss from torch import nn # 1. 定义输入和目标注意需要 float32 类型 inputs torch.tensor([1, 2, 3], dtypetorch.float32) targets torch.tensor([1, 2, 5], dtypetorch.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平均绝对误差默认 reductionmean loss_l1 L1Loss() result_l1 loss_l1(inputs, targets) print(fL1Loss: {result_l1}) # tensor(0.6667) # 4. L1Loss reductionsum loss_l1_sum L1Loss(reductionsum) result_l1_sum loss_l1_sum(inputs, targets) print(fL1Loss (sum): {result_l1_sum}) # tensor(2.) # 5. MSELoss均方误差 loss_mse MSELoss() result_mse loss_mse(inputs, targets) print(fMSELoss: {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(fCrossEntropyLoss: {result_cross}) # tensor(1.1019)1.inputs torch.tensor([1, 2, 3], dtypetorch.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个11|1-1| 0第2个22|2-2| 0第3个35|3-5| 2平均绝对误差 (0 0 2) / 3 0.66674.L1Loss(reductionsum)把平均绝对误差再求和此题就是0.6667*325. MSELoss均方误差先求每个位置的误差平方再求平均值计算过程位置预测值真实值误差预测-真实误差的平方第1个1100² 0第2个2200² 0第3个35-2(-2)² 4均方误差 (0 0 4) / 3 1.33336.CrossEntropyLoss交叉熵常用于分类x torch.tensor([0.1, 0.2, 0.3])是神经网络给出的三个图片的得分得分越高代表越像目前[0.1, 0.2, 0.3]表示012三类中2分数最高是0.3y 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