Побудова моделі «мішок слів»

Інженерія ознак для NLP у Python

Rounak Banik

Data Scientist

Підсумок формату даних для алгоритмів ML

Для будь-якого алгоритму ML,

  • Дані мають бути у табличному вигляді
  • Навчальні ознаки мають бути числові
Інженерія ознак для NLP у Python

Модель «мішок слів»

  • Виділіть токени слів
  • Обчисліть частоти токенів
  • Побудуйте вектор слів із цих частот і словника корпусу
Інженерія ознак для NLP у Python

Приклад моделі «мішок слів»

Корпус

"The lion is the king of the jungle"
"Lions have lifespans of a decade"
"The lion is an endangered species"
Інженерія ознак для NLP у Python

Приклад моделі «мішок слів»

Словник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]
Інженерія ознак для NLP у Python

Попередня обробка тексту

  • Lions, lionlion
  • The, thethe
  • Без пунктуації
  • Без стоп-слів
  • Менший словник
  • Менша розмірність покращує продуктивність
Інженерія ознак для NLP у Python

Модель «мішок слів» у sklearn

corpus = pd.Series([
    'The lion is the king of the jungle',
    'Lions have lifespans of a decade',
    'The lion is an endangered species'
])
Інженерія ознак для NLP у Python

Модель «мішок слів» у 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)
Інженерія ознак для NLP у Python

Давайте потренуємось!

Інженерія ознак для NLP у Python

Preparing Video For Download...