Budowanie modelu bag of words

Inżynieria cech dla NLP w Pythonie

Rounak Banik

Data Scientist

Format danych dla algorytmów ML

Dla każdego algorytmu ML,

  • Dane muszą być w formie tabelarycznej
  • Cechy treningowe muszą być liczbowe
Inżynieria cech dla NLP w Pythonie

Model bag of words

  • Wyodrębnienie tokenów słów
  • Obliczenie częstości tokenów
  • Budowa wektora słów na podstawie częstości i słownika korpusu
Inżynieria cech dla NLP w Pythonie

Przykład 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"
Inżynieria cech dla NLP w Pythonie

Przykład modelu bag of words

Słownika, 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]
Inżynieria cech dla NLP w Pythonie

Przetwarzanie tekstu

  • Lions, lionlion
  • The, thethe
  • Bez znaków interpunkcyjnych
  • Bez stopwords
  • Mniejsze słowniki
  • Redukcja wymiarów poprawia wydajność
Inżynieria cech dla NLP w Pythonie

Model bag of words w sklearn

corpus = pd.Series([
    'The lion is the king of the jungle',
    'Lions have lifespans of a decade',
    'The lion is an endangered species'
])
Inżynieria cech dla NLP w Pythonie

Model bag of words w 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)
Inżynieria cech dla NLP w Pythonie

Czas na ćwiczenia!

Inżynieria cech dla NLP w Pythonie

Preparing Video For Download...