PyTorch에서의 임베딩
PyBooks는 도서 추천 시스템으로 성과를 거두었지만, 텍스트에 담긴 일부 의미론을 반영하지는 못하고 있어요. PyTorch의 내장 임베딩 레이어는 데이터에서 직접 단어 간 관계를 학습하고 표현할 수 있습니다. 팀에서는 이 기능을 활용해 추천 시스템을 개선할 수 있는지 확인하고자 해요. 구현을 도와주실 수 있나요?
torch와 torch.nn(별칭 nn)은 이미 임포트되어 있어요.
이 연습은 강의의 일부입니다
PyTorch로 배우는 텍스트 딥러닝
연습 안내
words의 각 단어에 고유 인덱스를 매핑해word_to_idx에 저장하세요.word_to_idx를 PyTorch 텐서로 변환해inputs에 저장하세요.torch모듈을 사용해 차원 수가 10인 임베딩 레이어를 초기화하세요.- 임베딩 레이어에
inputs텐서를 전달하고 출력 결과를 확인하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Map a unique index to each word
words = ["This", "book", "was", "fantastic", "I", "really", "love", "science", "fiction", "but", "the", "protagonist", "was", "rude", "sometimes"]
word_to_idx = {word: ____ for i, word in enumerate(____)}
# Convert word_to_idx to a tensor
inputs = ____.____([word_to_idx[w] for w in words])
# Initialize embedding layer with ten dimensions
embedding = nn.____(num_embeddings=len(words), embedding_dim=____)
# Pass the tensor to the embedding layer
output = embedding(____)
print(output)