深度學(xué)習(xí)中,模型訓(xùn)練完后,查看模型的參數(shù)量和浮點計算量,在此記錄下:
1 THOP
在pytorch中有現(xiàn)成的包thop用于計算參數(shù)數(shù)量和FLOP,首先安裝thop:
注意安裝thop時可能出現(xiàn)如下錯誤:

解決方法:
pip install --upgrade git+https://github.com/Lyken17/pytorch-OpCounter.git # 下載源碼安裝
使用方法如下:
from torchvision.models import resnet50 # 引入ResNet50模型
from thop import profile
model = resnet50()
flops, params = profile(model, input_size=(1, 3, 224,224)) # profile(模型,輸入數(shù)據(jù))
對于自己構(gòu)建的函數(shù)也一樣,例如shuffleNetV2
from thop import profile
from utils.ShuffleNetV2 import shufflenetv2 # 導(dǎo)入shufflenet2 模塊
import torch
model_shuffle = shufflenetv2(width_mult=0.5)
model = torch.nn.DataParallel(model_shuffle) # 調(diào)用shufflenet2 模型,該模型為自己定義的
flop, para = profile(model, input_size=(1, 3, 224, 224),)
print("%.2fM" % (flop/1e6), "%.2fM" % (para/1e6))
更多細節(jié),可參考thop GitHub鏈接: https://github.com/Lyken17/pytorch-OpCounter
2 計算參數(shù)
pytorch本身帶有計算參數(shù)的方法
from thop import profile
from utils.ShuffleNetV2 import shufflenetv2 # 導(dǎo)入shufflenet2 模塊
import torch
model_shuffle = shufflenetv2(width_mult=0.5)
model = torch.nn.DataParallel(model_shuffle)
total = sum([param.nelement() for param in model.parameters()])
print("Number of parameter: %.2fM" % (total / 1e6))
補充:pytorch: 計算網(wǎng)絡(luò)模型的計算量(FLOPs)和參數(shù)量(Params)
計算量:
FLOPs,F(xiàn)LOP時指浮點運算次數(shù),s是指秒,即每秒浮點運算次數(shù)的意思,考量一個網(wǎng)絡(luò)模型的計算量的標準。
參數(shù)量:
Params,是指網(wǎng)絡(luò)模型中需要訓(xùn)練的參數(shù)總數(shù)。
第一步:安裝模塊(thop)
第二步:計算
import torch
from thop import profile
net = Model() # 定義好的網(wǎng)絡(luò)模型
input = torch.randn(1, 3, 112, 112)
flops, params = profile(net, (inputs,))
print('flops: ', flops, 'params: ', params)
注意:
輸入input的第一維度是批量(batch size),批量的大小不回影響參數(shù)量, 計算量是batch_size=1的倍數(shù)
profile(net, (inputs,))的 (inputs,)中必須加上逗號,否者會報錯
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:- PyTorch里面的torch.nn.Parameter()詳解
- Pytorch之parameters的使用
- Pytorch模型中的parameter與buffer用法