๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’ป Programming/AI & ML

[pytorch] model ์— ์ ‘๊ทผํ•˜๊ธฐ, ํŠน์ • layer ๋ณ€๊ฒฝํ•˜๊ธฐ

by ๋ญ…์ฆค 2022. 1. 5.
๋ฐ˜์‘ํ˜•

pytorch ๋ชจ๋ธ์— ์ ‘๊ทผํ•˜๊ณ  ํŠน์ • layer ๋˜๋Š” layer ๋‚ด๋ถ€์˜ ๋ชจ๋“ˆ์„ ๋ณ€๊ฒฝํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์ •๋ฆฌํ•œ๋‹ค.

- ์˜ˆ์‹œ ๋ชจ๋ธ : resnet50

 

import torch.nn as nn
import torchvision.models as models

model = models.resnet50(pretrained=True)

1. self.named_parameters() 

for name, param in model.layer1.named_parameters():
    print(name,param.shape,sep="   ")

 

2. self.named_children()

for name,ch in model.layer1.named_children():
    print("name :",name)
    print("child :", ch)
    print('===========================')

 

๋ฐ˜์‘ํ˜•

 

3. Model layer ๋ณ€๊ฒฝ

๋ชจ๋ธ์˜ ๋ฉค๋ฒ„๋ณ€์ˆ˜๋ฅผ return ํ•ด์ฃผ๋Š” named_children()์œผ๋กœ ๋ณ€๊ฒฝํ•˜๊ณ ์ž ํ•˜๋Š” layer๋ฅผ ์ฐพ๊ณ , ํด๋ž˜์Šค์˜ ๋ชจ๋“ˆ๋“ค์„ return ํ•ด์ฃผ๋Š” _modules๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ ‘๊ทผ.

print('model.layer1._modules[\'0\'] ๋ณ€๊ฒฝ ์ „ :', model.layer1._modules['0'],sep ='\n')
model.layer1._modules['0']._modules['conv1'] = nn.Conv2d(77,77,7)
print('model.layer1._modules[\'0\'] ๋ณ€๊ฒฝ ํ›„ :', model.layer1._modules['0'],sep ='\n')
print('model.layer1._modules[\'0\']._modules[\'conv1\'] ๋ณ€๊ฒฝ ํ›„ :',model.layer1._modules['0']._modules['conv1'],sep ='\n')

 

* ์ ‘๊ทผ ์˜ˆ์‹œ

Resnet50 ๋ชจ๋ธ์—์„œ layer1์˜ 0๋ฒˆ์งธ bottleneck์˜ downsample์˜ Conv2d ์—์„œ ์ ‘๊ทผํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” ์•„๋ž˜์™€ ๊ฐ™์ด -

model.layer1._modules['0']._modules['downsample']._modules['0']
๋ฐ˜์‘ํ˜•