pytorch自定義loss損失函數(shù)
自定義loss的方法有很多,但是在博主查資料的時候發(fā)現(xiàn)有挺多寫法會有問題,靠譜一點的方法是把loss作為一個pytorch的模塊,
比如:
class CustomLoss(nn.Module): # 注意繼承 nn.Module ? ? def __init__(self): ? ? ? ? super(CustomLoss, self).__init__() ? ? def forward(self, x, y): ? ? ? ? # .....這里寫x與y的處理邏輯,即loss的計算方法 ? ? ? ? return loss # 注意最后只能返回Tensor值,且?guī)荻?,?loss.requires_grad == True
示例代碼:
以一個pytorch求解線性回歸的代碼為例:
import torch
import torch.nn as nn
import numpy as np
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
def get_x_y():
? ? np.random.seed(0)
? ? x = np.random.randint(0, 50, 300)
? ? y_values = 2 * x + 21
? ? x = np.array(x, dtype=np.float32)
? ? y = np.array(y_values, dtype=np.float32)
? ? x = x.reshape(-1, 1)
? ? y = y.reshape(-1, 1)
? ? return x, y
class LinearRegressionModel(nn.Module):
? ? def __init__(self, input_dim, output_dim):
? ? ? ? super(LinearRegressionModel, self).__init__()
? ? ? ? self.linear = nn.Linear(input_dim, output_dim) ?# 輸入的個數(shù),輸出的個數(shù)
? ? def forward(self, x):
? ? ? ? out = self.linear(x)
? ? ? ? return out
if __name__ == '__main__':
? ? input_dim = 1
? ? output_dim = 1
? ? x_train, y_train = get_x_y()
? ? model = LinearRegressionModel(input_dim, output_dim)
? ? epochs = 1000 ?# 迭代次數(shù)
? ? optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
? ? model_loss = nn.MSELoss() # 使用MSE作為loss
? ? # 開始訓(xùn)練模型
? ? for epoch in range(epochs):
? ? ? ? epoch += 1
? ? ? ? # 注意轉(zhuǎn)行成tensor
? ? ? ? inputs = torch.from_numpy(x_train)
? ? ? ? labels = torch.from_numpy(y_train)
? ? ? ? # 梯度要清零每一次迭代
? ? ? ? optimizer.zero_grad()
? ? ? ? # 前向傳播
? ? ? ? outputs: torch.Tensor = model(inputs)
? ? ? ? # 計算損失
? ? ? ? loss = model_loss(outputs, labels)
? ? ? ? # 返向傳播
? ? ? ? loss.backward()
? ? ? ? # 更新權(quán)重參數(shù)
? ? ? ? optimizer.step()
? ? ? ? if epoch % 50 == 0:
? ? ? ? ? ? print('epoch {}, loss {}'.format(epoch, loss.item()))步驟1:添加自定義的類
我們就用自定義的寫法來寫與MSE相同的效果,MSE計算公式如下:

添加一個類:
class CustomLoss(nn.Module): ? ? def __init__(self): ? ? ? ? super(CustomLoss, self).__init__() ? ? ? ? self.mse_loss = nn.MSELoss() ? ? def forward(self, x, y): ? ? ? ? mse_loss = torch.mean(torch.pow((x - y), 2)) # x與y相減后平方,求均值即為MSE ? ? ? ? return mse_loss
步驟2:修改使用的loss函數(shù)
只需要把原始代碼中的:
model_loss = nn.MSELoss() # 使用MSE作為loss
改為:
model_loss = CustomLoss() ?# 自定義loss
即可
完整代碼:
import torch
import torch.nn as nn
import numpy as np
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
def get_x_y():
? ? np.random.seed(0)
? ? x = np.random.randint(0, 50, 300)
? ? y_values = 2 * x + 21
? ? x = np.array(x, dtype=np.float32)
? ? y = np.array(y_values, dtype=np.float32)
? ? x = x.reshape(-1, 1)
? ? y = y.reshape(-1, 1)
? ? return x, y
class LinearRegressionModel(nn.Module):
? ? def __init__(self, input_dim, output_dim):
? ? ? ? super(LinearRegressionModel, self).__init__()
? ? ? ? self.linear = nn.Linear(input_dim, output_dim) ?# 輸入的個數(shù),輸出的個數(shù)
? ? def forward(self, x):
? ? ? ? out = self.linear(x)
? ? ? ? return out
class CustomLoss(nn.Module):
? ? def __init__(self):
? ? ? ? super(CustomLoss, self).__init__()
? ? ? ? self.mse_loss = nn.MSELoss()
? ? def forward(self, x, y):
? ? ? ? mse_loss = torch.mean(torch.pow((x - y), 2))
? ? ? ? return mse_loss
if __name__ == '__main__':
? ? input_dim = 1
? ? output_dim = 1
? ? x_train, y_train = get_x_y()
? ? model = LinearRegressionModel(input_dim, output_dim)
? ? epochs = 1000 ?# 迭代次數(shù)
? ? optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
? ? # model_loss = nn.MSELoss() # 使用MSE作為loss
? ? model_loss = CustomLoss() ?# 自定義loss
? ? # 開始訓(xùn)練模型
? ? for epoch in range(epochs):
? ? ? ? epoch += 1
? ? ? ? # 注意轉(zhuǎn)行成tensor
? ? ? ? inputs = torch.from_numpy(x_train)
? ? ? ? labels = torch.from_numpy(y_train)
? ? ? ? # 梯度要清零每一次迭代
? ? ? ? optimizer.zero_grad()
? ? ? ? # 前向傳播
? ? ? ? outputs: torch.Tensor = model(inputs)
? ? ? ? # 計算損失
? ? ? ? loss = model_loss(outputs, labels)
? ? ? ? # 返向傳播
? ? ? ? loss.backward()
? ? ? ? # 更新權(quán)重參數(shù)
? ? ? ? optimizer.step()
? ? ? ? if epoch % 50 == 0:
? ? ? ? ? ? print('epoch {}, loss {}'.format(epoch, loss.item()))
到此這篇關(guān)于pytorch自定義loss損失函數(shù)的文章就介紹到這了,更多相關(guān)pytorch loss損失函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
PyTorch常用函數(shù)torch.cat()中dim參數(shù)使用說明
這篇文章主要為大家介紹了PyTorch常用函數(shù)torch.cat()中dim參數(shù)使用說明,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04
Python格式化輸出字符串方法小結(jié)【%與format】
這篇文章主要介紹了Python格式化輸出字符串方法,結(jié)合實例形式總結(jié)分析了使用%與format函數(shù)進行字符串格式化操作相關(guān)實現(xiàn)技巧與注意事項,需要的朋友可以參考下2018-10-10
python3編寫ThinkPHP命令執(zhí)行Getshell的方法
這篇文章主要介紹了python3編寫ThinkPHP命令執(zhí)行Getshell的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02
Python?threading中l(wèi)ock的使用詳解
Lock類是threading中用于鎖定當前線程的鎖定類,本文給大家介紹了Python?threading中l(wèi)ock的使用,需要的朋友可以參考下2022-11-11
python 實現(xiàn)關(guān)聯(lián)規(guī)則算法Apriori的示例
這篇文章主要介紹了python 實現(xiàn)關(guān)聯(lián)規(guī)則算法Apriori的示例,幫助大家更好的理解和學(xué)習python,感興趣的朋友可以了解下2020-09-09
python編程matplotlib交互繪制Julia集示例解析
matplotlib的Show面板中提供了放大、移動等交互式操作,但也未能涵蓋所有的交互需求,比如希望通過mandelbrot集上的一點來生成對應(yīng)的Julia集2021-10-10

