텍스트 데이터 인코딩

PyTorch로 배우는 텍스트 딥러닝

Shubham Jain

Data Scientist

텍스트 인코딩

파이토치 처리 파이프라인

  • 텍스트를 기계가 읽을 수 있는 수치로 변환
  • 분석과 모델링을 가능하게 함

통찰을 위한 순차 데이터 이미지

PyTorch로 배우는 텍스트 딥러닝

인코딩 기법

  • 원-핫 인코딩: 단어를 고유한 수치로 변환
  • Bag-of-Words(BoW): 순서를 무시하고 단어 빈도 포착
  • TF-IDF: 희소성과 중요도의 균형
  • 임베딩: 의미를 담은 벡터로 변환(2장)
PyTorch로 배우는 텍스트 딥러닝

원-핫 인코딩

  • 각 단어를 고유 벡터에 매핑
  • 이진 벡터:
    • 단어가 있으면 1
    • 없으면 0
  • ['cat', 'dog', 'rabbit']
    • 'cat' [1, 0, 0]
    • 'dog' [0, 1, 0]
    • 'rabbit' [0, 0, 1]
PyTorch로 배우는 텍스트 딥러닝

PyTorch로 원-핫 인코딩

import torch
vocab = ['cat', 'dog', 'rabbit']

vocab_size = len(vocab)
one_hot_vectors = torch.eye(vocab_size)
one_hot_dict = {word: one_hot_vectors[i] for i, word in enumerate(vocab)}
print(one_hot_dict)
{'cat': tensor([1., 0., 0.]),
  'dog': tensor([0., 1., 0.]),
  'rabbit': tensor([0., 0., 1.])}
PyTorch로 배우는 텍스트 딥러닝

Bag-of-words

  • 예: "The cat sat on the mat"
  • Bag-of-words:
    • {'the': 2, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1}
  • 각 문서를 순서 없는 단어 모음으로 처리
  • 순서가 아닌 빈도에 집중
PyTorch로 배우는 텍스트 딥러닝

CountVectorizer

from sklearn.feature_extraction.text import CountVectorizer

vectorizer = CountVectorizer()
corpus = ['This is the first document.', 'This document is the second document.', 'And this is the third one.', 'Is this the first document?']
X = vectorizer.fit_transform(corpus)
print(X.toarray())
print(vectorizer.get_feature_names_out())
[[0 1 1 1 0 0 1 0 1]
 [0 2 0 1 0 1 1 0 1]
 [1 0 0 1 1 0 1 1 1]
 [0 1 1 1 0 0 1 0 1]]

['and' 'document' 'first' 'is' 'one' 'second' 'the' 'third' 'this']
PyTorch로 배우는 텍스트 딥러닝

TF-IDF

  • Term Frequency-Inverse Document Frequency
    • 문서 내 단어 중요도를 점수화
    • 드문 단어는 높은 점수
    • 흔한 단어는 낮은 점수
    • 정보량 높은 단어를 강조
PyTorch로 배우는 텍스트 딥러닝

TfidfVectorizer

from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer()

corpus = ['This is the first document.','This document is the second document.', 'And this is the third one.','Is this the first document?']
X = vectorizer.fit_transform(corpus)
print(X.toarray())
print(vectorizer.get_feature_names_out())
[[0.         0.         0.68091856 0.51785612 0.51785612 0.        ]
 [0.         0.         0.          0.51785612 0.51785612 0.68091856]
 [0.85151335 0.42575668 0.         0.32274454 0.32274454 0.        ]
 [0.         0.         0.68091856 0.51785612 0.51785612 0.        ]]

['and' 'document' 'first' 'is' 'one' 'second']
PyTorch로 배우는 텍스트 딥러닝

TfidfVectorizer

TFIDF 코드

PyTorch로 배우는 텍스트 딥러닝

인코딩 기법

기법: 원-핫 인코딩, Bag-of-Words, TF-IDF

  • 모델이 텍스트를 이해·처리하도록 함
  • 중복을 피하려면 한 가지 기법만 선택
  • 더 많은 기법이 있음
PyTorch로 배우는 텍스트 딥러닝

Ayo berlatih!

PyTorch로 배우는 텍스트 딥러닝

Preparing Video For Download...