學習過程知識粗略記錄,用于個人了解和日後檢視
包導入
import torch
from torch import nn
MSELoss-均方差損失
- 常用于回歸問題中
- 對于每一個輸入執行個體都隻有一個輸出值,把所有輸入執行個體的預測值和真實值見的誤差求平方,然後取平均
- 定義:
class torch.nn.MSELoss(size_average=True,reduce=True)
參數含義
:預設為
size_average
,此時損失為每個
True
的平均;
minibatch
時,損失為每個
False
的求和。這個屬性隻有在
minibatch
設定為True時才生效
reduce
reduce
,損失根據
True
的值計算;
size_average
時,忽略
False
值,傳回每個元素的損失
size_average
loss=nn.MSELoss()
input = torch.randn(2, 3, requires_grad=True)
target = torch.randn(2,3)
print(input)
print(target)
output = loss(input, target)
output.backward()
print(output)

L1Loss-MAE平均絕對誤差
- 傳回資料集上所有誤差絕對值的平均數
-
,參數與class torch.nn.L1Loss(size_average=True,reduce=True)
相同MSE
loss=nn.L1Loss()
input = torch.randn(2, 3, requires_grad=True)
target = torch.randn(2,3)
print(input)
print(target)
output = loss(input, target)
output.backward()
print(output)
BCELoss
- 常用于二分類問題中
-
class torch.nn.BCELoss(weight=None, size_average=True, reduce=True)
參數定義:
:指定
weight
中的每個元素的
batch
權重,必須是一個長度和
Loss
相等的
batch
Tensor
- 值得注意的是,每個目标值都要求在
之間,可以在網絡最後一層加一個(0,1)
解決這個問題Sigmoid
m = nn.Sigmoid()
loss = nn.BCELoss()
input = torch.randn(3, requires_grad=True)
target = torch.empty(3).random_(2)
print(input)
print(target)
output = loss(m(input), target)
output.backward()
print(output)
BCEWithLogitsLoss
- 同樣用于二分類問題,他将
集合在了函數中,因而實際使用中會比Sigmoid
在數值上更加穩定BCELoss
-
,參數同class torch.nn.BCEWithLogitsLoss(weight=None, size_average=True, reduce=True)
一緻BCELoss
loss = nn.BCEWithLogitsLoss()
input = torch.randn(3, requires_grad=True)
target = torch.empty(3).random_(2)
print(input)
print(target)
output = loss(input, target)
output.backward()
print(output)
NLLLoss-負對數似然損失函數
- 應用于多分類任務中,用C表示多分類任務中的類别個數,
表示N
,則minibatch
的輸入必須是NLLLoss
的二維(N,C)
,也就是每個執行個體對應的每個類别的對數機率,可以在網絡的最後一層加Tensor
層來實作LogSoftmax
- 定義:
class torch.nn.NLLLoss(weight=None, size_average=True, ignore_index=-100,reduce=True)
參數含義:
:指定一個一維的
weight
,用來設定每個類别的權重(非必須項)
Tensor
:設定一個被忽略值,使這個值不會影響到輸入的梯度計算,
ignore_index
為
size_average
時,
True
的平均值也會忽略該值
loss
- 值得注意的時,輸入根據
而定,reduce
則輸出一個标量,True
則輸出False
N
m = nn.LogSoftmax(dim=1)
loss = nn.NLLLoss()
# input is of size N x C = 3 x 5
input = torch.randn(3, 5, requires_grad=True)
# each element in target has to have 0 <= value < C
target = torch.tensor([1, 0, 4])
print(input)
print(target)
output = loss(m(input), target)
output.backward()
print(output)
CrossEntropyLoss-交叉熵損失
- 用于多分類問題,
和LogSoftmax
的組合NLLLoss
-
,參數含義與class torch.nn.CrossEntropyLoss(weight=None, size_average=True, ignore_index=-100,reduce=True)
NLLLoss
loss = nn.CrossEntropyLoss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.empty(3, dtype=torch.long).random_(5)
print(input)
print(target)
output = loss(input, target)
output.backward()
print(output)
如有錯誤,歡迎指正
同時釋出在CSDN中:https://blog.csdn.net/tangkcc/article/details/119803598