Neural Network

안소희·2024년 10월 11일

PyTorch

목록 보기
5/8

신경망은 데이터를 처리하는 계층이나 모듈로 이뤄져 있다. PyTorch의 torch.nn이 필요한 모든걸 제공한다. 그리고 모든 모듈은 nn.Modulel을 상속받는다

학습 장치 고르기

가능하면 GPU나 MPS 같은 하드웨어 가속기로 모델을 학습시키자.

device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"

클래스 만들기

신경망 모델은 nn.Module을 상속받아 만든다. __init__에서 계층들을 초기화하고, forward에서 데이터 처리 과정을 구현한다

class NeuralNetwork(nn.Module):
    def __init__(self):
        super().__init__()
        self.flatten = nn.Flatten()
        self.linear_relu_stack = nn.Sequential(
            nn.Linear(28*28, 512),
            nn.ReLU(),
            nn.Linear(512, 512),
            nn.ReLU(),
            nn.Linear(512, 10),
        )

    def forward(self, x):
        x = self.flatten(x)
        logits = self.linear_relu_stack(x)
        return logits

모델 계층 (Layer)

  • nn.Flatten: 2D 이미지를 1D 배열로 바꿈
    flatten = nn.Flatten()
    flat_image = flatten(input_image)
    print(flat_image.size())
    # 출력: torch.Size([3, 784])
  • nn.Linear: 입력에 선형 변환을 적용
    layer1 = nn.Linear(in_features=28*28, out_features=20)
    hidden1 = layer1(flat_image)
    print(hidden1.size())
    # 출력: torch.Size([3, 20])
  • nn.ReLU: 비선형 활성화 함수. 복잡한 패턴을 학습
    print(f"Before ReLU: {hidden1}")
    hidden1 = nn.ReLU()(hidden1)
    print(f"After ReLU: {hidden1}")
  • nn.Sequential: 여러 모듈을 순서대로 실행해주는 컨테이너
    seq_modules = nn.Sequential(
        flatten,
        layer1,
        nn.ReLU(),
        nn.Linear(20, 10)
    )
    input_image = torch.rand(3, 28, 28)
    logits = seq_modules(input_image)
  • nn.Softmax: 출력을 확률 분포로 변환
    softmax = nn.Softmax(dim=1)
    pred_probab = softmax(logits)

모델 매개변수

named_parameters() 메소드로 모델의 모든 파라미터를 볼 수 있다. 각 파라미터의 크기와 값을 확인할 수 있다

profile
인공지능.관심 있습니다.

0개의 댓글