侧边栏壁纸
博主头像
lmg博主等级

  • 累计撰写 55 篇文章
  • 累计创建 6 个标签
  • 累计收到 2 条评论
标签搜索

pytorch

lmg
lmg
2019-04-11 / 0 评论 / 0 点赞 / 383 阅读 / 715 字
温馨提示:
本文最后更新于 2022-04-16,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

损失函数

1. CrossEntropyloss

a.交叉熵损失函数,常用于分类
b.用这个loss前面不需要加 softmax层
c.该函数限制了target的类型为torch.LongTensor

import torch as t
from torch import nn
from torch.autograd import Variable as V
# batch_size=4, 计算每个类别分数(二分类)
output = V(t.randn(4,2)) # batch_size * C=(batch_size, C)
# target必须是LongTensor!
target =V(t.Tensor([1,0,1,1])).long()

criterion = nn.CrossEntropyLoss()
loss = criterion(output, target)
print('loss', loss)

output: loss tensor(1.0643)

2. toch.nn.MSELoss

均方损失函数,类似于nn.L1Loss函数:
MSELoss

import torch
loss_fn = torch.nn.MSELoss(reduce=False, size_average=False)
input = torch.autograd.Variable(torch.randn(3,4))
target = torch.autograd.Variable(torch.randn(3,4))
loss = loss_fn(input, target)
print(input); print(target); print(loss)
print(input.size(), target.size(), loss.size())

output:

0

评论区