การสร้างโมเดล Bag of Words

Feature Engineering for NLP in Python

Rounak Banik

Data Scientist

ทบทวนรูปแบบข้อมูลสำหรับอัลกอริทึม ML

สำหรับอัลกอริทึม ML ทุกประเภท

  • ข้อมูลต้องอยู่ในรูปแบบตาราง
  • ฟีเจอร์สำหรับ training ต้องเป็นตัวเลข
Feature Engineering for NLP in Python

โมเดล Bag of Words

  • ดึง token คำออกมา
  • คำนวณความถี่ของ token คำ
  • สร้าง word vector จากความถี่และ vocabulary ของ corpus
Feature Engineering for NLP in Python

ตัวอย่างโมเดล Bag of Words

Corpus

"The lion is the king of the jungle"
"Lions have lifespans of a decade"
"The lion is an endangered species"
Feature Engineering for NLP in Python

ตัวอย่างโมเดล Bag of Words

Vocabulary → a, an, decade, endangered, have, is, jungle, king, lifespans, lion, Lions, of, species, the, The

"The lion is the king of the jungle"
[0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 2, 1]
"Lions have lifespans of a decade"
[1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0]
"The lion is an endangered species"
[0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1]
Feature Engineering for NLP in Python

การประมวลผลข้อความเบื้องต้น

  • Lions, lion → lion
  • The, the → the
  • ไม่มีเครื่องหมายวรรคตอน
  • ไม่มี stopword
  • ทำให้ vocabulary มีขนาดเล็กลง
  • การลด dimension ช่วยเพิ่มประสิทธิภาพ
Feature Engineering for NLP in Python

โมเดล Bag of Words ด้วย sklearn

corpus = pd.Series([
    'The lion is the king of the jungle',
    'Lions have lifespans of a decade',
    'The lion is an endangered species'
])
Feature Engineering for NLP in Python

โมเดล Bag of Words ด้วย sklearn

# Import CountVectorizer
from sklearn.feature_extraction.text import CountVectorizer

# Create CountVectorizer object vectorizer = CountVectorizer()
# Generate matrix of word vectors bow_matrix = vectorizer.fit_transform(corpus) print(bow_matrix.toarray())
array([[0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 3],
       [0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0],
       [1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1]], dtype=int64)
Feature Engineering for NLP in Python

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

Feature Engineering for NLP in Python

Preparing Video For Download...