본문으로 건너뛰기

[메타코드 강의 후기] 딥러닝 Deep Learning | Neural Network (2)

LEGGO약 2 분DeepLearningPytorchLinearLayerSoftmaxActivationFunctionMatrixMultiplication메타코드메타코드mmetacodemetacodem

메타코드 강의: 딥러닝 입문 + Pytorch 실습 부트캠프로 이동open in new window
메타코드 강의: 딥러닝 입문 + Pytorch 실습 부트캠프로 이동

메타코드?

메타코드는 IT 대기업 현직자 + 서울대/카이스트 AI 박사 등 검증된 강사진들로 구성되어 있으며,

현직자 특강, 커리어 멘토링, 포트폴리오, 공모전, 채용정보 등 실제 취업에 도움이 될 수 있는 양질의 컨텐츠를 제공하고 있습니다.


Multiplication 실습

요소별 곱셈 (Element-wise Multiplication)

  • 함수: torch.mul 또는 * 연산자
  • 설명: 두 텐서의 동일한 위치에 있는 요소들을 곱합니다. 이 연산을 수행하기 위해서는 두 텐서의 크기가 동일하거나 브로드캐스팅이 가능해야 합니다.
  • 예시:
    a = torch.tensor([1, 2, 3])
    b = torch.tensor([4, 5, 6])
    c = torch.mul(a, b)  # 또는 c = a * b
    # tensor([ 4, 10, 18])
    

2. 행렬 곱셈 (Matrix Multiplication)

  • 함수: torch.matmul 또는 @ 연산자
  • 설명: 두 행렬의 행렬 곱셈을 수행합니다. 첫 번째 행렬의 열 수와 두 번째 행렬의 행 수가 일치해야 합니다. 높은 차원의 텐서에 대해서는 배치 행렬 곱셈을 수행할 수 있습니다.
  • 예시:
    x = torch.tensor([[1, 2], [3, 4]])
    y = torch.tensor([[5, 6], [7, 8]])
    z = torch.matmul(x, y)  # 또는 z = x @ y
    # tensor([[19, 22],
    #       [43, 50]])
    

3. 외적 (Outer Product)

  • 함수: torch.ger (1차원 벡터에 대해서만 적용됨)
  • 설명: 두 벡터의 외적을 계산합니다. 결과는 두 벡터의 외적에 의해 형성된 행렬입니다.
  • 예시:
    u = torch.tensor([1, 3, 5])
    v = torch.tensor([2, 4, 6])
    w = torch.ger(u, v)
    # tensor([[ 2,  4,  6],
    #       [ 6, 12, 18],
    #       [10, 20, 30]])
    

4. 점곱 (Dot Product)

  • 함수: torch.dot
  • 설명: 두 1차원 벡터의 점곱을 계산합니다. 두 벡터의 요소별 곱의 합입니다.
  • 예시:
    a = torch.tensor([1, 2, 3])
    b = torch.tensor([4, 5, 6])
    c = torch.dot(a, b)
    # tensor(32)
    

5. 배치 행렬 곱셈 (Batch Matrix Multiplication)

  • 함수: torch.bmm
  • 설명: 배치(batch) 형태의 텐서들의 행렬 곱셈을 수행합니다. 각 배치의 개별 행렬들은 독립적으로 곱셈을 수행합니다.
  • 예시:
    batch1 = torch.randn(10, 3, 4)
    batch2 = torch.randn(10, 4, 5)
    result = torch.bmm(batch1, batch2)
    # tensor([[[ 1.9656, -1.4797,  0.4503,  2.1843, -1.3143],
    #        [-0.3299,  2.2563, -4.4555,  3.1269,  0.7716],
    #        [ 0.4057,  0.0654, -0.7291,  1.8528, -0.8565]],
    # 
    #       [[ 0.3334, -2.2051,  1.2494,  3.1999, -1.4396],
    #        [-0.0404, -0.6591, -0.8889, -0.3918,  0.1977],
    #        [ 0.0626, -0.8335,  1.1534,  1.4029, -0.1824]],
    # 
    #       [[-2.5646, -0.9155,  0.9574,  1.4331, -1.8319],
    #        [ 0.3659,  0.7177, -2.2157,  5.8017,  1.2782],
    #        [ 0.8371, -1.8774,  1.2041, -4.2432, -0.0179]],
    # 
    #       [[ 1.5131,  1.6859, -0.5711,  0.9276, -4.2848],
    #        [ 5.0313,  0.0715,  2.1567,  1.8968, -2.1191],
    #        [-0.9673, -0.7816,  0.5175,  1.4824,  0.6211]]])
    

Linear Layer 실습

nn.Module를 사용한 사용자 정의 선형 레이어

사용자가 직접 선형 레이어를 구현할 수 있습니다. 아래 예제에서는 가중치와 편향을 파라미터로 받아, 입력과 매트릭스 연산을 수행하는 간단한 선형 레이어를 구현합니다.

import torch
import torch.nn as nn

# 사용자 정의 Linear Layer
class MyLinear(nn.Module):
    def __init__(self, input_dim, output_dim):
        super(MyLinear, self).__init__()
        self.W = nn.Parameter(torch.randn(input_dim, output_dim))
        self.b = nn.Parameter(torch.randn(output_dim))
    
    def forward(self, x):
        return torch.matmul(x, self.W) + self.b

# 모델 생성 및 입력 데이터 정의
my_linear = MyLinear(4, 3)
input_tensor = torch.randn(2, 4)

# 레이어 실행
output = my_linear(input_tensor)
print("Custom Linear Output:")
print(output)
# Custom Linear Output:
# tensor([[-1.5095,  0.8142,  1.7202],
#         [ 0.1201,  1.4879, -0.9357]], grad_fn=<AddBackward0>)

nn.Linear를 사용한 선형 레이어

nn.Linear 모듈은 선형 변환을 수행하는 레이어를 제공합니다. 이 모듈은 자동으로 가중치와 편향을 초기화하며, 역전파를 통해 이들을 학습할 수 있도록 설정됩니다.

# Linear Layer
builtin_linear = nn.Linear(4, 3)
output_builtin = builtin_linear(input_tensor)

# 레이어 실행
print("Built-in Linear Output:")
print(output_builtin)
# Built-in Linear Output:
# tensor([[ 0.5612, -0.1629, -0.4694],
#         [ 0.6485,  0.1707, -0.1371]], grad_fn=<AddmmBackward0>)

두 방식 모두 같은 기능을 수행하지만, nn.Linear 레이어를 사용하는 것이 초기화, 관리, 그리고 확장성 측면에서 더 편리합니다.

Activation Function 실습

Sigmoid

Sigmoid 함수는 입력 값을 0과 1 사이의 값으로 변환합니다. 주로 이진 분류 문제에서 출력 레이어의 활성화 함수로 사용됩니다.

import torch.nn.functional as F
import torch

sigmoid_input = torch.randn(2, 3)
sigmoid_output = F.sigmoid(sigmoid_input)
print(sigmoid_input)
print(sigmoid_output)
# 예시 출력:
# tensor([[-0.2970,  0.9734, -0.6172],
#         [ 0.8511, -2.0110,  0.2973]])
# tensor([[0.4263, 0.7257, 0.3507],
#         [0.7009, 0.1177, 0.5738]])

ReLU

ReLU (Rectified Linear Unit) 함수는 음수 값을 모두 0으로 처리하고, 양수 값은 그대로 출력합니다. 이는 비선형성을 도입하며, 널리 사용되는 활성화 함수 중 하나입니다.

relu_input = torch.randn(2, 3)
relu_output = F.relu(relu_input)
print(relu_input)
print(relu_output)
# 예시 출력:
# tensor([[ 0.4312, -0.5106,  1.3609],
#         [-0.0343, -0.4968,  0.3364]])
# tensor([[0.4312, 0.0000, 1.3609],
#         [0.0000, 0.0000, 0.3364]])

Softmax

Softmax 함수는 벡터의 각 요소를 0과 1 사이의 값으로 변환하고, 모든 요소의 합을 1로 만듭니다. 주로 다중 클래스 분류 문제에서 출력 레이어의 활성화 함수로 사용됩니다.

softmax_input = torch.randn(2, 3)
softmax_output = F.softmax(softmax_input, dim=1)
print(softmax_input)
print(softmax_output)
# 예시 출력:
# tensor([[ 0.8653, -0.3656,  0.3593],
#         [ 1.4948, -1.3673, -0.6775]])
# tensor([[0.4641, 0.1361, 0.3998],
#         [0.8099, 0.0469, 0.1432]])

이런 분들께 추천합니다!


서포터즈 강의료 지원을 받아 작성하였습니다