網(wǎng)站首頁 編程語言 正文
自定義loss
的方法有很多,但是在博主查資料的時(shí)候發(fā)現(xiàn)有挺多寫法會(huì)有問題,靠譜一點(diǎn)的方法是把loss作為一個(gè)pytorch的模塊,
比如:
class CustomLoss(nn.Module): # 注意繼承 nn.Module ? ? def __init__(self): ? ? ? ? super(CustomLoss, self).__init__() ? ? def forward(self, x, y): ? ? ? ? # .....這里寫x與y的處理邏輯,即loss的計(jì)算方法 ? ? ? ? return loss # 注意最后只能返回Tensor值,且?guī)荻?,?loss.requires_grad == True
示例代碼:
以一個(gè)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) ?# 輸入的個(gè)數(shù),輸出的個(gè)數(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) ? ? ? ? # 計(jì)算損失 ? ? ? ? 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計(jì)算公式如下:
添加一個(gè)類:
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) ?# 輸入的個(gè)數(shù),輸出的個(gè)數(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) ? ? ? ? # 計(jì)算損失 ? ? ? ? loss = model_loss(outputs, labels) ? ? ? ? # 返向傳播 ? ? ? ? loss.backward() ? ? ? ? # 更新權(quán)重參數(shù) ? ? ? ? optimizer.step() ? ? ? ? if epoch % 50 == 0: ? ? ? ? ? ? print('epoch {}, loss {}'.format(epoch, loss.item()))
原文鏈接:https://blog.csdn.net/weixin_35757704/article/details/122865272
相關(guān)推薦
- 2022-09-08 Python報(bào)錯(cuò)SyntaxError:unexpected?EOF?while?parsing的解
- 2023-03-17 Python控制windows系統(tǒng)音量實(shí)現(xiàn)實(shí)例_python
- 2022-07-13 @postconstruct注解 和 InitializingBean 在bean實(shí)例化后執(zhí)行某些初
- 2022-11-01 go項(xiàng)目打包部署的完整步驟_Golang
- 2023-10-15 字符串逆序輸出,編譯器優(yōu)化,循環(huán)代碼外提,無效代碼刪除
- 2022-12-07 C語言內(nèi)存分布與heap空間分別詳細(xì)講解_C 語言
- 2022-12-11 Go語言實(shí)現(xiàn)棧與隊(duì)列基本操作學(xué)家_Golang
- 2023-03-28 python如何實(shí)現(xiàn)向上取整_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支