การแทนค่าแบบ Bag-of-Words

การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

Fouad Trad

Machine Learning Engineer

ทบทวน NLP workflow

ไดอะแกรมแสดง workflow ทั้งหมด โดยระบุว่าบทที่ 3 และ 4 เน้นที่ไลบรารี transformers

การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

Bag-of-Words (BoW)

  • เทคนิคพื้นฐานในการแทนข้อความด้วยตัวเลข
  • แทนข้อความโดยนับความถี่ของแต่ละคำ
  • โยนคำทั้งหมดลง "ถุง" แล้วนับ
  • ไม่สนใจไวยากรณ์และลำดับคำ

ภาพแสดงคำในข้อความถูกโยนลงถุง จากนั้นนับจำนวนการปรากฏของแต่ละคำ

การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

ตัวอย่าง BoW

ภาพแสดงสองประโยค: 'I love NLP' และ 'I love machine learning.'

การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

ตัวอย่าง BoW

ภาพแสดง vocabulary ที่สร้างจากประโยค ได้แก่ I, love, NLP, machine และ learning

  • สร้าง vocabulary จากคำที่ไม่ซ้ำกันทั้งหมด
การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

ตัวอย่าง BoW

ภาพแสดง feature vector ของแต่ละประโยค ซึ่งสร้างโดยการนับจำนวนคำตาม vocabulary ที่กำหนด

  • สร้าง vocabulary จากคำที่ไม่ซ้ำกันทั้งหมด
  • นับจำนวนครั้งที่แต่ละคำใน vocabulary ปรากฏ
การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

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']
การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

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']
การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

ผลลัพธ์ของ 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)>

Sparse matrix: ตารางที่ส่วนใหญ่เต็มไปด้วยศูนย์

การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

ผลลัพธ์ของ 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']
การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

ความถี่ของคำ

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()

กราฟแท่งแสดงคำและความถี่ โดย stop words มีความถี่สูงสุด

การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

มาฝึกกันเถอะ!

การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

Preparing Video For Download...