pytorch的nn.MSELoss损失函数

均方损失函数:

loss(xi,yi)=(xiyi)2 loss ( x i , y i ) = ( x i − y i ) 2

这里 loss, x, y 的维度是一样的,可以是向量或者矩阵,i 是下标。

很多的 loss 函数都有 size_average 和 reduce 两个布尔类型的参数。因为一般损失函数都是直接计算 batch 的数据,因此返回的 loss 结果都是维度为 (batch_size, ) 的向量。

(1)如果 reduce = False,那么 size_average 参数失效,直接返回向量形式的 loss
(2)如果 reduce = True,那么 loss 返回的是标量
a)如果 size_average = True,返回 loss.mean();
b)如果 size_average = False,返回 loss.sum();

注意:默认情况下, reduce = True,size_average = True

import torch
import numpy as np

1、返回向量

loss_fn = torch.nn.MSELoss(reduce=False, size_average=False)
a=np.array([[1,2],[3,4]])
b=np.array([[2,3],[4,5]])
input = torch.autograd.Variable(torch.from_numpy(a))
target = torch.autograd.Variable(torch.from_numpy(b))

这里将Variable类型统一为float()(tensor类型也是调用xxx.float())

loss = loss_fn(input.float(), target.float())
print(loss)
tensor([[ 1.,  1.],
        [ 1.,  1.]])

2、返回平均值

a=np.array([[1,2],[3,4]])
b=np.array([[2,3],[4,4]])
loss_fn = torch.nn.MSELoss(reduce=True, size_average=True)
input = torch.autograd.Variable(torch.from_numpy(a))
target = torch.autograd.Variable(torch.from_numpy(b))
loss = loss_fn(input.float(), target.float())
 print(loss)
tensor(0.7500)
  • 101
    点赞
  • 321
    收藏
    觉得还不错? 一键收藏
  • 17
    评论
nn.MSELoss函数是用于计算均方误差(Mean Squared Error)的函数。在深度学习中,该函数通常用于评估模型输出与目标值之间的差异。具体来说,该函数计算输入和目标之间每个元素差值的平方,并求取这些平方值的均值作为损失值。 该函数的使用方法如下: ``` import torch loss_function = torch.nn.MSELoss(reduction='mean') loss = loss_function(input, target) ``` 其中,input和target分别是MSELoss的两个输入,reduction参数指定了计算损失的方式,这里使用了默认值'mean',表示计算均值作为损失值。 需要注意的是,使用该函数时,一般只需要将reduction参数设置为'mean',而其他参数无需调整。此外,该函数是逐元素计算的,即对输入和目标的每个元素进行损失计算,并返回一个标量作为最终的损失值。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [详解Pytorch中的torch.nn.MSELoss函,包括对每个参数的分析!](https://blog.csdn.net/qq_40968179/article/details/128260036)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [深度学习中常用的损失函数(一) —— MSELoss()](https://blog.csdn.net/weixin_44558721/article/details/127396925)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值