日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

nn.损失函数

發布時間:2024/3/12 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 nn.损失函数 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

nn.L1Loss

https://pytorch.org/docs/stable/generated/torch.nn.L1Loss.html#torch.nn.L1Loss
例子:
input=[1,3,4]
target=[2,3,7]
則loss=(|2-1|+|3-3|+|7-4|)/3=4/3=1.333

import torch from torch import nninput = torch.tensor([1, 3, 4],dtype=torch.float) target = torch.tensor([2, 3, 7],dtype=torch.float) loss_fn1 = nn.L1Loss() loss1 = loss_fn1(input, target) print("loss1:{}".format(loss1)) loss1:1.3333333730697632

其中可以加入參數,求和,默認是求平均

loss_fn2=nn.L1Loss(reduction='sum') loss2=loss_fn2(input,target) print("loss2:{}".format(loss2)) loss2:4.0

nn.MSELoss

均方差損失函數
https://pytorch.org/docs/stable/generated/torch.nn.MSELoss.html#torch.nn.MSELoss
input=[1,3,4]
target=[2,3,7]
loss=(2-1)**2+(3-3)**2+(7-4)**2=0+9+1=10

loss_fn3=nn.MSELoss() loss3=loss_fn3(input,target) print("loss3:{}".format(loss3)) loss3:3.3333332538604736

默認求平均,即10/3=3.3333,可通過指定進行求和

loss_fn4=nn.MSELoss(reduction='sum') loss4=loss_fn4(input,target) print("loss4:{}".format(loss4)) loss4:10.0

交叉熵損失函數 CrossEntropyLoss

https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html#torch.nn.CrossEntropyLoss
計算公式為:

比如對于一個3分類的圖片,假設最終結果input為[0.2, 0.6 , 0.3],而正確的標簽為1,即第2個,注意這是單個圖片,input的尺寸為1x3,
此時的loss計算為:-x[1]+ln(exp(x[1])+exp(x[2])+exp(x[3])=-0.6+ln(exp(0.2)+exp(0.6)+exp(0.3))=0.88009

input=torch.tensor([0.2,0.6,0.3]) target=torch.tensor([1]) loss_fn=nn.CrossEntropyLoss() input=torch.reshape(input,[1,3]) #1是指1個batchsize loss=loss_fn(input,target) print(loss) tensor(0.8801)

要注意輸入格式

如果batchsize為N,則input為NxC,C為有幾個分類,target為1xN,結果默認是取平均,即除以batchsize的大小

比如:
input=【【0.2, 0.6 , 0.3】
【0.5,0.1,0.7】】
target=【1,2】
第二行的loss=0.8618,
兩行取平均,(0.8801+0.8618)/2=0.8709

input=torch.tensor([[0.2,0.6,0.3],[0.5,0.1,0.7]]) target=torch.tensor([1,2]) loss_fn=nn.CrossEntropyLoss() loss=loss_fn(input,target) print(loss) tensor(0.8710)

https://www.bilibili.com/video/BV1hE411t7RN?p=23

總結

以上是生活随笔為你收集整理的nn.损失函数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。