구릅 코랩과 챗지피티가 아니었다면, 머신러닝을 지나 딥러닝/NLP까지 도착하지는 못했을 것이다. 늘 고맙게 감사하게 생각한다.
torch.nn.Embedding에서 _weight 옵션은 임베딩 행렬의 초기값을 설정하는 데 사용됩니다. 이 매개변수는 주로 Embedding.from_pretrained() 메서드 내부에서 사용되며, 사용자가 직접 임베딩 행렬을 지정할 수 있습니다.
기본 동작
nn.Embedding을 생성할 때 _weight를 명시적으로 설정하면, 해당 값을 임베딩 행렬로 사용합니다. 이를 통해 사전 학습된 임베딩(예: GloVe, FastText)을 모델 초기화에 활용할 수 있습니다.
_weight 매개변수
- 타입: torch.Tensor
- 크기: (num_embeddings, embedding_dim)
- num_embeddings: 사전에 포함된 고유 토큰 수.
- embedding_dim: 각 토큰의 임베딩 벡터 차원.
- 역할: 초기 임베딩 행렬로 사용되며, 학습 가능 여부는 모델 설정에 따라 달라집니다.
- 주의: _weight는 Embedding 객체를 초기화할 때만 사용할 수 있으며, 이후에는 접근하거나 수정할 수 없습니다.
사용 예제
1. _weight를 수동으로 설정
import torch
import torch.nn as nn
# 사용자 지정 임베딩 행렬 (사전 학습된 값 예시)
pretrained_weights = torch.tensor([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]])
# nn.Embedding 초기화 시 _weight 설정
embedding = nn.Embedding(num_embeddings=3, embedding_dim=2, _weight=pretrained_weights)
# 입력 데이터
input_indices = torch.tensor([0, 2])
output = embedding(input_indices)
print(output)
# 출력: [[0.1, 0.2], [0.5, 0.6]]
2. from_pretrained()와 비교
Embedding.from_pretrained()는 _weight를 설정하는 더 편리한 방법입니다.
# 동일한 pretrained_weights 사용
embedding = nn.Embedding.from_pretrained(pretrained_weights)
# 입력 데이터
input_indices = torch.tensor([0, 2])
output = embedding(input_indices)
print(output)
# 출력: [[0.1, 0.2], [0.5, 0.6]]
사전 학습된 임베딩 사용
_weight를 활용하면 사전 학습된 임베딩을 쉽게 사용할 수 있습니다. 예를 들어, GloVe나 FastText 임베딩을 가져와 torch.Tensor로 변환한 뒤 _weight에 전달하면 됩니다.
import numpy as np
# 사전 학습된 GloVe 임베딩 (numpy 배열)
pretrained_glove = np.array([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]])
# torch.Tensor로 변환
pretrained_weights = torch.tensor(pretrained_glove)
# _weight로 초기화
embedding = nn.Embedding(num_embeddings=3, embedding_dim=2, _weight=pretrained_weights)
# 입력 데이터
input_indices = torch.tensor([1])
output = embedding(input_indices)
print(output)
# 출력: [[0.3, 0.4]]
_weight의 학습 가능 여부
- _weight로 설정된 임베딩 행렬은 기본적으로 학습 가능합니다.
- 학습을 방지하려면 from_pretrained()의 freeze=True를 사용하거나, 수동으로 파라미터를 고정해야 합니다:
embedding = nn.Embedding.from_pretrained(pretrained_weights, freeze=True)
요약
- _weight는 초기 임베딩 행렬을 지정하는 데 사용됩니다.
- 주로 사전 학습된 임베딩을 사용할 때 활용됩니다.
- 학습 가능 여부를 설정하려면 추가적인 설정이 필요합니다.
더 자세한 사항이나 추가적인 질문이 있다면 알려주세요! 😊
'Python, PySpark' 카테고리의 다른 글
RNN in python with Keras, PyTorch (0) | 2025.01.20 |
---|---|
NewsClassifier (0) | 2025.01.04 |
Python Scheduler (0) | 2024.12.10 |
networkx - sql과 함께 (0) | 2024.10.24 |
Python networkx (1) | 2024.10.10 |