Bag-of-Words 표현

Python으로 배우는 Natural Language Processing (NLP)

Fouad Trad

Machine Learning Engineer

NLP 워크플로 복습

전체 워크플로 다이어그램: 3, 4장은 transformers 라이브러리에 초점.

Python으로 배우는 Natural Language Processing (NLP)

Bag-of-Words (BoW)

  • 텍스트를 숫자로 표현하는 기본 기법
  • 각 단어의 등장 횟수로 텍스트를 표현합니다
  • 단어를 가방에 넣고 개수를 셉니다
  • 문법과 순서를 무시합니다

텍스트의 단어를 가방에 던지고 각 단어의 등장 횟수를 세는 그림.

Python으로 배우는 Natural Language Processing (NLP)

BoW 예시

두 문장: 'I love NLP'와 'I love machine learning.'

Python으로 배우는 Natural Language Processing (NLP)

BoW 예시

문장에서 도출된 어휘: I, love, NLP, machine, learning.

  • 모든 고유 단어로 어휘집을 만듭니다
Python으로 배우는 Natural Language Processing (NLP)

BoW 예시

정의한 어휘에 따라 각 문장의 단어 수로 생성된 특성 벡터.

  • 모든 고유 단어로 어휘집을 만듭니다
  • 어휘의 각 단어가 몇 번 나타나는지 셉니다
Python으로 배우는 Natural Language Processing (NLP)

코드로 보는 BoW

reviews = ["I loved the movie. It was amazing!",
           "The movie was okay.",
           "I hated the movie. It was boring."]

def preprocess(text):
text = text.lower()
tokens = word_tokenize(text)
tokens = [word for word in tokens if word not in string.punctuation]
return " ".join(tokens)
cleaned_reviews = [preprocess(review) for review in reviews]
print(cleaned_reviews)
['i loved the movie it was amazing', 
 'the movie was okay', 
 'i hated the movie it was boring']
Python으로 배우는 Natural Language Processing (NLP)

코드로 보는 BoW

from sklearn.feature_extraction.text import CountVectorizer


vectorizer = CountVectorizer()
vectorizer.fit(cleaned_reviews)
print(vectorizer.get_feature_names_out())
['amazing' 'boring' 'hated' 'it' 'loved' 'movie' 'okay' 'the' 'was']
Python으로 배우는 Natural Language Processing (NLP)

BoW 출력

X = vectorizer.transform(cleaned_reviews)

# OR X = vectorizer.fit_transform(cleaned_reviews)
print(X)
<Compressed Sparse Row sparse matrix of dtype 'int64'
    with 16 stored elements and shape (3, 9)>

희소 행렬: 대부분이 0인 행렬

Python으로 배우는 Natural Language Processing (NLP)

BoW 출력

print(X.toarray())
[[1 0 0 1 1 1 0 1 1]
 [0 0 0 0 0 1 1 1 1]
 [0 1 1 1 0 1 0 1 1]]
print(vectorizer.get_feature_names_out())
['amazing' 'boring' 'hated' 'it' 'loved' 'movie' 'okay' 'the' 'was']
Python으로 배우는 Natural Language Processing (NLP)

단어 빈도

import numpy as np

word_counts = np.sum(X.toarray(), axis=0)
words = vectorizer.get_feature_names_out()
import matplotlib.pyplot as plt

plt.bar(words, word_counts)
plt.title("Word Frequencies in Movie Reviews")
plt.xlabel("Words") plt.ylabel("Frequency") plt.show()

막대그래프: 단어와 빈도. 불용어가 가장 빈번함.

Python으로 배우는 Natural Language Processing (NLP)

연습해 봅시다!

Python으로 배우는 Natural Language Processing (NLP)

Preparing Video For Download...