Een bag-of-wordsmodel bouwen

Feature Engineering voor NLP in Python

Rounak Banik

Data Scientist

Herhaling: data-indeling voor ML-algoritmes

Voor elk ML-algoritme geldt:

  • Data moet tabulair zijn
  • Trainfeatures moeten numeriek zijn
Feature Engineering voor NLP in Python

Bag-of-wordsmodel

  • Extraheer woordtokens
  • Bereken frequentie per token
  • Maak een woordvector van deze frequenties en de corpuswoordenschat
Feature Engineering voor NLP in Python

Voorbeeld bag-of-wordsmodel

Corpus

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

Voorbeeld bag-of-wordsmodel

Woordenlijsta, 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 voor NLP in Python

Tekstvoorbewerking

  • Lions, lionlion
  • The, thethe
  • Geen leestekens
  • Geen stopwoorden
  • Leidt tot kleinere woordenlijsten
  • Minder dimensies verbetert prestaties
Feature Engineering voor NLP in Python

Bag-of-words met 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 voor NLP in Python

Bag-of-words met sklearn

# Import CountVectorizer
from sklearn.feature_extraction.text import CountVectorizer

# Maak een CountVectorizer-object vectorizer = CountVectorizer()
# Genereer matrix met woordvectoren 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 voor NLP in Python

Laten we oefenen!

Feature Engineering voor NLP in Python

Preparing Video For Download...