使用PyTorch構(gòu)建神經(jīng)網(wǎng)絡(luò),并使用thop計算參數(shù)和FLOPs
FLOPs和FLOPS區(qū)別
FLOPs(floating point operations)是指浮點運算次數(shù),通常用來評估一個計算機算法或者模型的計算復雜度。在機器學習中,F(xiàn)LOPs通常用來衡量神經(jīng)網(wǎng)絡(luò)的計算復雜度,因為神經(jīng)網(wǎng)絡(luò)的計算主要由矩陣乘法和卷積操作組成,而這些操作都可以轉(zhuǎn)化為浮點運算次數(shù)的形式進行計算。
FLOPS(floating point operations per second)是指每秒鐘可以執(zhí)行的浮點運算次數(shù),通常用來評估一個計算機系統(tǒng)的計算能力。在機器學習中,F(xiàn)LOPS也可以用來衡量計算機系統(tǒng)的性能,因為神經(jīng)網(wǎng)絡(luò)的訓練和推斷需要大量的浮點運算,計算機系統(tǒng)的FLOPS越高,就越能夠快速地完成神經(jīng)網(wǎng)絡(luò)的計算任務(wù)。
需要注意的是,F(xiàn)LOPs和FLOPS都是衡量計算復雜度和計算能力的指標,但它們的單位不同,F(xiàn)LOPs的單位是次,而FLOPS的單位是次/秒。FLOPs和FLOPS是兩個不同的概念,F(xiàn)LOPs是指浮點運算次數(shù),而FLOPS是指每秒鐘可以執(zhí)行的浮點運算次數(shù)。在實際應(yīng)用中,我們通常會同時考慮這兩個指標,以評估計算機算法或者模型在不同的計算機系統(tǒng)上的表現(xiàn)。
使用PyTorch搭建神經(jīng)網(wǎng)絡(luò)
整體代碼
import torch
import torch.nn as nn
from torchsummary import summary
from thop import profile, clever_format
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class MyNet(nn.Module):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1)
self.relu1 = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1)
self.relu2 = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv3 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)
self.relu3 = nn.ReLU(inplace=True)
self.conv4 = nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1)
self.relu4 = nn.ReLU(inplace=True)
self.fc1 = nn.Linear(128*8*8, 1024)
self.relu5 = nn.ReLU(inplace=True)
self.fc2 = nn.Linear(1024, 10)
def forward(self, x):
x = self.conv1(x)
x = self.relu1(x)
x = self.conv2(x)
x = self.relu2(x)
x = self.maxpool(x)
x = self.conv3(x)
x = self.relu3(x)
x = self.conv4(x)
x = self.relu4(x)
x = x.view(-1, 128*8*8)
x = self.fc1(x)
x = self.relu5(x)
x = self.fc2(x)
return x
net = MyNet().to(device)
input_shape = (3, 224, 224)
summary(net, input_shape)
input_tensor = torch.randn(1, *input_shape).to(device)
flops, params = profile(net, inputs=(input_tensor,))
flops, params = clever_format([flops, params], "%.3f")
print("FLOPs: %s" %(flops))
print("params: %s" %(params))
這段代碼是一個使用PyTorch實現(xiàn)的卷積神經(jīng)網(wǎng)絡(luò)。下面是一步一步的教程:
1. 導入必要的庫
import torch
import torch.nn as nn
from torchsummary import summary
from thop import profile, clever_format
其中,torch
是PyTorch深度學習框架的核心庫,torch.nn
是PyTorch中神經(jīng)網(wǎng)絡(luò)相關(guān)的模塊,torchsummary
是用于打印網(wǎng)絡(luò)結(jié)構(gòu)的庫,thop
是用于計算網(wǎng)絡(luò)FLOPs和參數(shù)數(shù)量的庫。
2. 定義神經(jīng)網(wǎng)絡(luò)模型
class MyNet(nn.Module):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1)
self.relu1 = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1)
self.relu2 = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv3 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)
self.relu3 = nn.ReLU(inplace=True)
self.conv4 = nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1)
self.relu4 = nn.ReLU(inplace=True)
self.fc1 = nn.Linear(128*8*8, 1024)
self.relu5 = nn.ReLU(inplace=True)
self.fc2 = nn.Linear(1024, 10)
def forward(self, x):
x = self.conv1(x)
x = self.relu1(x)
x = self.conv2(x)
x = self.relu2(x)
x = self.maxpool(x)
x = self.conv3(x)
x = self.relu3(x)
x = self.conv4(x)
x = self.relu4(x)
x = x.view(-1, 128*8*8)
x = self.fc1(x)
x = self.relu5(x)
x = self.fc2(x)
return x
這個網(wǎng)絡(luò)模型包括了4個卷積層、2個全連接層和ReLU激活函數(shù)。其中,nn.Conv2d
是PyTorch中的二維卷積層,nn.ReLU
是ReLU激活函數(shù)層,nn.MaxPool2d
是最大池化層,nn.Linear
是全連接層。這個模型的輸入是一個3通道、224x224大小的圖像,輸出是一個10維的向量,分別表示輸入圖像屬于10個不同的類別的概率。
3. 打印網(wǎng)絡(luò)結(jié)構(gòu)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
net = MyNet().to(device)
input_shape = (3, 224, 224)
summary(net, input_shape)
這里我們首先根據(jù)設(shè)備是否支持CUDA來選擇使用CPU或GPU,然后將模型實例化為net
并將其放到設(shè)備上。接著,我們定義輸入圖像的形狀為(3, 224, 224),然后使用summary
函數(shù)打印網(wǎng)絡(luò)的結(jié)構(gòu)信息,包括每一層的輸入和輸出形狀、參數(shù)數(shù)量等。
4. 計算網(wǎng)絡(luò)FLOPs和參數(shù)數(shù)量
input_tensor = torch.randn(1, *input_shape).to(device)
flops, params = profile(net, inputs=(input_tensor,))
flops, params = clever_format([flops, params], "%.3f")
print("FLOPs: %s" %(flops))
print("params: %s" %(params))
這里我們使用隨機生成的輸入圖像進行前向傳播,然后使用profile
函數(shù)計算網(wǎng)絡(luò)的FLOPs和參數(shù)數(shù)量。inputs
參數(shù)接受一個元組,其中包含了網(wǎng)絡(luò)的輸入,這里我們將隨機生成的輸入圖像封裝成一個元組傳入。計算完成后,使用clever_format
函數(shù)將FLOPs和參數(shù)數(shù)量格式化成易讀的字符串形式,最后打印出來。
5. 結(jié)果如下
----------------------------------------------------------------
Layer (type) Output Shape Param #
================================================================
Conv2d-1 [-1, 64, 224, 224] 1,792
ReLU-2 [-1, 64, 224, 224] 0
Conv2d-3 [-1, 64, 224, 224] 36,928
ReLU-4 [-1, 64, 224, 224] 0
MaxPool2d-5 [-1, 64, 112, 112] 0
Conv2d-6 [-1, 128, 112, 112] 73,856
ReLU-7 [-1, 128, 112, 112] 0
Conv2d-8 [-1, 128, 112, 112] 147,584
ReLU-9 [-1, 128, 112, 112] 0
Linear-10 [-1, 1024] 8,389,632
ReLU-11 [-1, 1024] 0
Linear-12 [-1, 10] 10,250
================================================================
Total params: 8,660,042
Trainable params: 8,660,042
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.57
Forward/backward pass size (MB): 153.14
Params size (MB): 33.04
Estimated Total Size (MB): 186.75
----------------------------------------------------------------
[INFO] Register count_convNd() for <class 'torch.nn.modules.conv.Conv2d'>.
[INFO] Register zero_ops() for <class 'torch.nn.modules.activation.ReLU'>.
[INFO] Register zero_ops() for <class 'torch.nn.modules.pooling.MaxPool2d'>.
[INFO] Register count_linear() for <class 'torch.nn.modules.linear.Linear'>.
FLOPs: 6.357G
params: 8.660M
這段代碼定義了一個簡單的卷積神經(jīng)網(wǎng)絡(luò)模型,然后使用thop
庫計算模型的FLOPs(浮點運算次數(shù))和參數(shù)數(shù)量。
手動計算params
好的,這里是每一層的參數(shù)計算公式:
- Conv2d層:參數(shù)數(shù)量 = (輸入通道數(shù) x 卷積核高度 x 卷積核寬度 x 輸出通道數(shù)) + 輸出通道數(shù)
- Linear層:參數(shù)數(shù)量 = 輸入大小 x 輸出大小 + 輸出大小
- 沒有參數(shù)的層(如ReLU和MaxPool)不需要計算參數(shù)數(shù)量。
具體來說,在這個神經(jīng)網(wǎng)絡(luò)中,每一層的參數(shù)計算公式和參數(shù)數(shù)量如下:
- Conv2d-1:(3 x 3 x 3 x 64) + 64 = 1,792
- ReLU-2:沒有參數(shù)
- Conv2d-3:(3 x 3 x 64 x 64) + 64 = 36,928
- ReLU-4:沒有參數(shù)
- MaxPool2d-5:沒有參數(shù)
- Conv2d-6:(3 x 3 x 64 x 128) + 128 = 73,856
- ReLU-7:沒有參數(shù)
- Conv2d-8:(3 x 3 x 128 x 128) + 128 = 147,584
- ReLU-9:沒有參數(shù)
- Linear-10:(128 x 56 x 56 x 1024) + 1024 = 8,389,632
- ReLU-11:沒有參數(shù)
- Linear-12:(1024 x 10) + 10 = 10,250
總參數(shù)數(shù)為8,660,042個。
手動計算FLOPs
Thop(PyTorch-OpCounter)是一個用于計算PyTorch模型浮點運算量(FLOPs)的庫,它可以自動計算模型中每個操作的FLOPs,包括卷積層、池化層、全連接層等。
在Thop中,F(xiàn)LOPs的計算基于每個操作的輸入張量大小、輸出張量大小以及操作的參數(shù)數(shù)量。具體地,對于一個卷積層,F(xiàn)LOPs的計算公式為:
F L O P s = 2 × k 2 × C i n × C o u t × H o u t × W o u t s t r i d e 2 FLOPs = 2 \times k^2 \times C_{in} \times C_{out} \times \frac{H_{out} \times W_{out}}{stride^2} FLOPs=2×k2×Cin?×Cout?×stride2Hout?×Wout??
其中, k k k 是卷積核大小, C i n C_{in} Cin? 是輸入通道數(shù), C o u t C_{out} Cout? 是輸出通道數(shù), H o u t H_{out} Hout? 和 W o u t W_{out} Wout? 是輸出特征圖的高度和寬度, s t r i d e stride stride 是步幅。這個公式中的常數(shù)2表示每個卷積操作需要2次乘法(一個是卷積核和輸入的卷積,另一個是卷積結(jié)果和偏置的加法),因此需要乘以2。
對于其他層類型,Thop使用不同的公式計算FLOPs。例如,對于全連接層,F(xiàn)LOPs的計算公式為:
F L O P s = 2 × C i n × C o u t FLOPs = 2 \times C_{in} \times C_{out} FLOPs=2×Cin?×Cout?
其中, C i n C_{in} Cin? 和 C o u t C_{out} Cout? 分別是輸入和輸出的特征數(shù)量。
通過使用Thop庫,您可以方便地計算模型的總體FLOPs,以評估模型的計算復雜度和性能。
池化層和ReLU層的計算復雜度相對簡單,可以用以下公式進行計算:
對于池化層,假設(shè)輸入特征圖大小為 W 1 × H 1 W_1\times H_1 W1?×H1?,池化尺寸為 k × k k\times k k×k,步幅為 s s s,則池化層的FLOPs計算公式為:
F L O P s = W 2 × H 2 × C × k 2 FLOPs = W_2\times H_2\times C\times k^2 FLOPs=W2?×H2?×C×k2
其中, W 2 = ? ( W 1 ? k ) / s ? + 1 W_2=\lfloor(W_1-k)/s\rfloor+1 W2?=?(W1??k)/s?+1, H 2 = ? ( H 1 ? k ) / s ? + 1 H_2=\lfloor(H_1-k)/s\rfloor+1 H2?=?(H1??k)/s?+1, C C C 是輸入特征圖的通道數(shù)。這個公式中的常數(shù) k 2 k^2 k2表示每個池化操作需要 k × k k\times k k×k次取最大值。
對于ReLU層,假設(shè)輸入特征圖大小為 W × H × C W\times H\times C W×H×C,ReLU層的計算量可以近似為:
F L O P s = W × H × C FLOPs = W\times H\times C FLOPs=W×H×C
這是因為ReLU激活函數(shù)的計算本身非常簡單,只需要比較輸入數(shù)據(jù)與0,然后保留大于0的值即可,因此單個ReLU激活函數(shù)的計算量可以視為常數(shù)。
需要注意的是,這些公式只是近似計算,實際的計算復雜度可能會因為不同實現(xiàn)方式、硬件平臺等因素而有所不同。對于更準確的計算,可以使用一些工具庫(如Thop)來進行計算。
為了解釋為什么得到的FLOPs是6.357G,我們需要逐層分析模型中的計算量。以下是計算步驟(不考慮relu和pool層):
- conv1: (3 × 3 × 3) × 64 × 224 × 224 = 86,704,128 FLOPs
- relu1: 0 FLOPs(ReLU激活函數(shù)的計算量通常不計入FLOPs) # 3211264
- conv2: (3 × 3 × 64) × 64 × 224 × 224 = 1,849,688,064 FLOPs
- relu2: 0 FLOPs # 3211264
- maxpool: 0 FLOPs(池化操作的計算量通常不計入FLOPs) # 32111254
- conv3: (3 × 3 × 64) × 128 × 112 × 112 = 924,844,032 FLOPs
- relu3: 0 FLOPs 128112112=1605632
- conv4: (3 × 3 × 128) × 128 × 112 × 112 = 1,849,688,064 FLOPs
- relu4: 0 FLOPs # 1605632
- fc1: 128 × 8 × 8 × 1024 = 8,388,608 FLOPs
- relu5: 0 FLOPs # 這個計算FLOPs我懵了。按20480吧
- fc2: 1024 × 10 = 10,240 FLOPs
將各層的FLOPs相加,得到總的FLOPs:
86,704,128 + 1,849,688,064 + 924,844,032 + 1,849,688,064 + 8,388,608 + 10240 = 4,719,323,136 FLOPs
然后將FLOPs轉(zhuǎn)換為GigaFLOPs(10^9 FLOPs):
4,719,323,136 / 10^9 ≈ 4.719 GigaFLOPs
4.719遠遠不等于6.357啊!
如果按照全部乘以2,又變成9點多了,又遠遠超過6.357了。
聽說profile算出來的FLOPs也需要乘以2。按照這么想的話,咱們手動計算的結(jié)果不乘2應(yīng)該和thop計算出來的相當。但是結(jié)果相當打臉,遠遠不等。
所以relu層和pool層肯定帶入FLOPs了。
為了計算方便和準確性,實際并沒有多大意義。你可太會說話了。
恩。。。怎么說呢
注意
顯然,結(jié)果與代碼中計算得到的6.357G不符。這就有點奇怪了?
消失的1.638G去哪里了?
就是把relu層和池化層的全部加上也不夠??!加上relu和池化層的結(jié)果如下。
86,704,128 + 3211264 + 1,849,688,064 + 3211254 + 32111254 + 924,844,032 + 1605632 + 1,849,688,064 + 1605632 + 8,388,608 + 10240 + 10240 = 4,761,078,412 FLOPs
relu和maxpool再怎么套公式,也算不上去了,加不了那么多。算了。。。。以后有時間再慢慢算吧,誰和thop計算的一樣可以留言公式,我去學習一下。文章來源:http://www.zghlxwxcb.cn/news/detail-775608.html
G去哪里了?
就是把relu層和池化層的全部加上也不夠??!加上relu和池化層的結(jié)果如下。
86,704,128 + 3211264 + 1,849,688,064 + 3211254 + 32111254 + 924,844,032 + 1605632 + 1,849,688,064 + 1605632 + 8,388,608 + 10240 + 10240 = 4,761,078,412 FLOPs
relu和maxpool再怎么套公式,也算不上去了,加不了那么多。算了。。。。以后有時間再慢慢算吧,誰和thop計算的一樣可以留言公式,我去學習一下。
**可能原因:**這可能是因為thop
庫在計算FLOPs時考慮了一些其他因素,relu和pool也計算進去了,而且占比還挺多,莫名增加了1.638G。因此,實際計算得到的FLOPs可能會與手動計算的結(jié)果有所不同。即使如此,手動計算的結(jié)果可以幫助我們理解FLOPs的大致數(shù)量級。文章來源地址http://www.zghlxwxcb.cn/news/detail-775608.html
到了這里,關(guān)于使用PyTorch構(gòu)建神經(jīng)網(wǎng)絡(luò),并使用thop計算參數(shù)和FLOPs的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!