網站首頁 編程語言 正文
一、基本
(1)利用pytorch建好的層進行搭建
import torch
from torch import nn
from torch.nn import functional as F
#定義一個MLP網絡
class MLP(nn.Module):
'''
網絡里面主要是要定義__init__()、forward()
'''
def __init__(self):
'''
這里定義網絡有哪些層(比如nn.Linear,Conv2d……)[可不含激活函數]
'''
super().__init__()#調用Module(父)初始化
self.hidden = nn.Linear(5,10)
self.out = nn.Linear(10,2)
def forward(self,x):
'''
這里定義前向傳播的順序,即__init__()中定義的層是按怎樣的順序進行連接以及傳播的[在這里加上激活函數,以構造復雜函數,提高擬合能力]
'''
return self.out(F.relu(self.hidden(x)))
上面的3層感知器可以用于解決一個簡單的現實問題:給定5個特征,輸出0-1類別概率值,是一個簡單的2分類解決方案。
搭建一些簡單的網絡時,可以用nn.Sequence(層1,層2,……,層n)一步到位:
import torch
from torch import nn
from torch.nn import functional as F
net = nn.Sequential(nn.Linear(5,10),nn.ReLU(),nn.Linear(10,2))
但是nn.Sequence僅局限于簡單的網絡搭建,而自定義網絡可以實現復雜網絡結構。
(1)中定義的MLP大致如上(5個輸入->全連接->ReLU()->輸出)
(2)使用網絡
import torch
from torch import nn
from torch.nn import functional as F
net = MLP()
x = torch.randn((15,5))#15個samples,5個輸入屬性
out = net(x)
#也可調用forward->"out = net.forward(x)"
print(out)
#print(out.shape)
tensor([[-0.0760, -0.1026],
[-0.3277, -0.2332],
[-0.0314, -0.1921],
[ 0.0131, -0.1473],
[-0.0650, -0.2310],
[ 0.3009, -0.5510],
[ 0.1491, -0.0928],
[-0.1438, -0.1304],
[-0.1945, -0.1944],
[ 0.1088, -0.2249],
[ 0.0016, -0.2334],
[ 0.1401, -0.3709],
[-0.1864, -0.1764],
[ 0.0775, -0.0160],
[ 0.0150, -0.3198]], grad_fn=<AddmmBackward>)
二、進階
(1)構建較復雜的網絡結構
a. Sequence、net套娃
import torch
from torch import nn
from torch.nn import functional as F
class MLP2(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(nn.Linear(5,10),nn.ReLU(),nn.Linear(10,5))
self.out = nn.Linear(5,4)
def forward(self,x):
return self.out(F.relu(self.net(x)))
net2 = nn.Sequential(MLP2(),nn.ReLU(),nn.Linear(4,2))
net2.eval()
# eval()等價print(net2)
Sequential(
(0): MLP2(
(net): Sequential(
(0): Linear(in_features=5, out_features=10, bias=True)
(1): ReLU()
(2): Linear(in_features=10, out_features=5, bias=True)
)
(out): Linear(in_features=5, out_features=4, bias=True)
)
(1): ReLU()
(2): Linear(in_features=4, out_features=2, bias=True)
)
(2) 參數
a. 權重、偏差的訪問
#訪問權重和偏差
print(net2[2].weight)#注意weight是parameter類型,.data訪問數值
print(net2[2].bias.data)
#輸出所有權重、偏差
print(*[(name,param) for name,param in net2[2].parameters()])
b. 不同網絡之間共享參數
shared = nn.Linear(8,8)
net = nn.Sequential(nn.Linear(5,8),nn.ReLU(),shared,nn.ReLU(),shared)
print(net[2].weight.data[0])
net[2].weight.data[0][0] = 100
print(net[2].weight.data[0][0])
print(net[2].weight.data[0] == net[4].weight.data[0])
net.eval()
c. 參數初始化
def init_Linear(m):
if type(m) == nn.Linear:
nn.init.normal_(m.weight,mean = 0,std = 0.01) #將權重按照均值為0,標準差為0.01的正態分布進行初始化
nn.init.zeros_(m.bias) #將偏差置為0
def init_const(m):
if type(m) == nn.Linear:
nn.init.constant_(m.weight,42) #將權重全部置為42
def my_init(m):
if type(m) == nn.Linear:
'''
對weight和bias自定義初始化
'''
pass
#如何調用?
net2.apply(init_const) #在net2中進行遍歷,對每個Linear執行初始化
(3)自定義層(__init__()中可含輸入輸出層)
a. 不帶輸入輸出的自定義層(輸入輸出一致,x數進,x數出,對每個值進行相同的操作,類似激活函數)
b. 帶輸入輸出的自定義層
import torch
from torch import nn
from torch.nn import functional as F
#a
class decentralized(nn.Module):
def __init__(self):
super().__init__()
def forward(self,x):
return x-x.mean()
#b
class my_Linear(nn.Module):
def __init__(self,dim_in,dim_out):
super().__init__()
self.weight = nn.Parameter(torch.ones(dim_in,dim_out)) #由于x行數為dim_out,列數為dim_in,要做乘法,權重行列互換
self.bias = nn.Parameter(torch.randn(dim_out))
def forward(self,x):
return F.relu(torch.matmul(x,self.weight.data)+self.bias.data)
tmp = my_Linear(5,3)
print(tmp.weight)
(4)讀寫
#存取任意torch類型變量
x = torch.randn((20,20))
torch.save(x,'X') #存
y = torch.load('X') #取
#存儲網絡
torch.save(net2.state_dict(),'Past_parameters') #把所有參數全部存儲
clone = nn.Sequential(MLP2(),nn.ReLU(),nn.Linear(4,2)) #存儲時同時存儲網絡定義(網絡結構)
clone.load_state_dict(torch.load('Past_parameters'))
clone.eval()
原文鏈接:https://www.cnblogs.com/BGM-WCJ/p/16695133.html
相關推薦
- 2022-03-19 使用Docker搭建MQTT服務器的過程詳解_docker
- 2022-07-18 RabbitMQ隊列阻塞該如何處理
- 2022-03-29 python中apply函數詳情_python
- 2022-11-13 C語言在輸入輸出時遇到的常見問題總結_C 語言
- 2024-02-29 UNI-APP中webview加載狀態,開始加載,加載完成事件監聽
- 2023-05-14 Python實現批量導入1000條xlsx數據_python
- 2022-04-28 shell?腳本中獲取命令的輸出的實現示例_linux shell
- 2022-07-26 淺談Redis的事件驅動模型_Redis
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支