PyTorch에서 Weight를 초기화하는 방법
코드와 대화형 시각화(Interactive visualization)를 사용하여 PyTorch에서Weight(가중치)를 초기화하는 방법의 간단한 튜토리얼
Created on August 15|Last edited on August 17
Comment
목차
목차우리가 함께 알아볼 내용클래스 기능(Class Function)이 있는 PyTorch에서 가중치를 0으로 초기화하기Pytorch Weight 초기화 실험요약Weights & Biases를 사용해 보세요추천 읽기 자료
우리가 함께 알아볼 내용
이번 게시글에서는 PyTorch 모델의 다양한 레이어에 대한 가중치를 초기화할 수 있는 방법에 대해 알아보겠습니다.
Tensorflow와 달리 PyTorch는 다양한 레이어에서 가중치를 초기화하는 쉬운 인터페이스를 제공하지 않기 때문에(torch.nn.init가 유행이긴 하지만), Xavier 또는 He Initialization과 같은 유명한 기술에 따라 가중치를 초기화하려고 할 때 좀 까다로워집니다.
아래에서 가중치를 초기화하는 방법에 대해 알아볼 예정이며, 실행 파일인 Colab을 사용하려면 다음에서 수행할 수 있습니다:
💡
클래스 기능(Class Function)이 있는 PyTorch에서 가중치를 0으로 초기화하기
가중치를 초기화하는 가장 일반적인 방법 중 하나는 사용자 지정 PyTorch 모델에서 __init__ 기능의 끝에 적용할 수 있는 클래스 함수를 사용하는 것입니다.
import torch.nn as nnclass Model(nn.Module):# . . .def __init__(self):# .self.apply(self._init_weights)def _init_weights(self, module):if isinstance(module, nn.Linear):module.weight.data.normal_(mean=0.0, std=1.0)if module.bias is not None:module.bias.data.zero_()
이 코드의 정보 조각은 평균이 0이고 표준 편차 1인 정규 분포의 모든 가중치를 초기화하고 모든 편향을 0으로 초기화합니다. 이를 nn.LayerNorm 과 nn.Embedding와 같은 다른 레이어로 확장하는 것은 매우 쉽습니다.
def _init_weights(self, module):if isinstance(module, nn.Embedding):module.weight.data.normal_(mean=0.0, std=1.0)if module.padding_idx is not None:module.weight.data[module.padding_idx].zero_()elif isinstance(module, nn.LayerNorm):module.bias.data.zero_()module.weight.data.fill_(1.0)
Pytorch Weight 초기화 실험
아래의Weights & Biases 차트는 가중치 초기화를 더 잘 설명하기 위해 제공된 것으로 코랩에서 추출한 것입니다. 다음에서 찾아볼 수 있습니다:
여기서는 정규 분포의 다양한 표준 편차가 ��능 측면에서 서로 얼마나 다른지 확인할 수 있습니다.
표준 편차 값이 크면 좋은 결과가 나오지 않으며 로컬 최소값이 발생할 가능성이 높습니다. 반면에 값이 작을수록 성능이 훨씬 향상됩니다.
요약
이 기사에서는 PyTorch 딥 러닝 모델에 대한 가중치를 초기화하는 방법과 Weights & Biases을 사용하여 메트릭을 모니터링하는 방법을 살펴보았습니다.
W&B의 모든 기능을 보려면 이 짧은 5분 가이드를 참조하십시오. 수학 및 "처음부터 시작하는" 코드 구현에 대한 더 많은 내용을 원하신다면 아래 또는 포럼 ✨에 댓글을 달아주세요!
Weights & Biases를 사용해 보세요
Weights & Biases는 머신 러닝 실험을 추적하는 데 도움을 드립니다. 저희 툴을 사용하여 실행에서 하이퍼 파라미터와 아웃풋 메트릭스를 기록한 다음 결과를 시각화하고 비교하고 여러분의 동료와 신속하게 결과를 공유해보세요.
5분 안에 시작해보거나 리플릿(Replit)에서 2개의 빠른 실험을 실행하고 W&B가 아래 설명에 따라 작업을 구성하는 데 어떻게 도움이 되는지 확인해보세요.
설명:
- 아래의 녹색 "실행" 버튼을 클릭 (처음 "실행"을 클릭했을 때, 머신을 할당하는 데 약 30-45초가 소요됩니다).
- 터미널 윈도우에 표시되는 메시지를 따릅니다(아래 오른쪽 하단 창).
- 터미널 윈도우의 크기를 조정하여 더 크게 볼 수 있습니다(오른쪽 아래).
추천 읽기 자료
How To Use GPU with PyTorch
A short tutorial on using GPUs for your deep learning models with PyTorch, from checking availability to visualizing usable.
A Gentle Introduction To Weight Initialization for Neural Networks
An explainer and comprehensive overview of various strategies for neural network weight initialization
PyTorch Dropout for regularization - tutorial
Learn how to regularize your PyTorch model with Dropout, complete with a code tutorial and interactive visualizations
How to save and load models in PyTorch
This article is a machine learning tutorial on how to save and load your models in PyTorch using Weights & Biases for version control.
Image Classification Using PyTorch Lightning and Weights & Biases
This article provides a practical introduction on how to use PyTorch Lightning to improve the readability and reproducibility of your PyTorch code.
How to Compare Keras Optimizers in Tensorflow for Deep Learning
A short tutorial outlining how to compare Keras optimizers for your deep learning pipelines in Tensorflow, with a Colab to help you follow along.
Add a comment
Iterate on AI agents and models faster. Try Weights & Biases today.