Vytvoření modelu bag of words

Feature Engineering for NLP in Python

Rounak Banik

Data Scientist

Formát dat pro algoritmy ML

Pro každý algoritmus ML

  • Data musí být ve tabulkové podobě
  • Trénovací příznaky musí být numerické
Feature Engineering for NLP in Python

Model bag of words

  • Extrahovat slovní tokeny
  • Vypočítat frekvenci slovních tokenů
  • Sestavit slovní vektor z těchto frekvencí a slovníku korpusu
Feature Engineering for NLP in Python

Příklad modelu bag of words

Korpus

"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

Příklad modelu bag of words

Slovníka, 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

Předzpracování textu

  • Lions, lionlion
  • The, thethe
  • Bez interpunkce
  • Bez stop slov
  • Vede k menším slovníkům
  • Snížení počtu dimenzí zlepšuje výkon
Feature Engineering for NLP in Python

Model bag of words pomocí 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

Model bag of words pomocí 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

Pojďme si procvičit!

Feature Engineering for NLP in Python

Preparing Video For Download...