본문 바로가기

Data-science/deep learning

pytorch에서 특정 layer freeze 하기 (학습하지 않기) freezing

반응형
for param in model.parameters():
    param.requires_grad = False

--> 이 방법은 pretrained model을 로드할 때는 쓰기 어렵다. 초기에 frozen되지 않은 layer에 대해서만 작동함. 정확하게 이게 무슨 말일까???

--> 여튼 위 방법은 pretrained에서 특정 layer를 얼리고 학습하거나 하면 어려울 수 있으니, 아래 방법을 소개한다.

The basic idea is that all models have a function model.children() which returns it’s layers. Within each layer, there are parameters (or weights), which can be obtained using .param() on any children (i.e. layer). Now, every parameter has an attribute called requires_grad which is by default True. True means it will be backpropagrated and hence to freeze a layer you need to set requires_grad to False for all parameters of a layer. This can be done like this -

모든 모델은 children이란 멤버함수를 가지는데, 이건 layer들을 반환해주는 함수다.

 각 레이어 내에서 파라미터가 있고, 레이어마다 .param 함수를 호출해줌으로써 이를 얻을 수 있다. 모든 파라미터는 requires_grad라는 특정성을 가진다. 이 특성의 기본값은 True인데, 역전파를 하겠다는 말이다. 그래서 한 레이어를 얼리려면 requires_grad를 False로 설정할 필요가 있다. 이건 아래와 같은 코드에서 이루어질 수 있다,

model_ft = models.resnet50(pretrained=True)
ct = 0
for child in model_ft.children():
ct += 1
if ct < 7:
    for param in child.parameters():
        param.requires_grad = False

discuss.pytorch.org/t/how-the-pytorch-freeze-network-in-some-layers-only-the-rest-of-the-training/7088

 

How the pytorch freeze network in some layers, only the rest of the training?

How the pytorch freeze network in some layers, only the rest of the training?

discuss.pytorch.org

 

반응형