Ein Bag-of-Words-Modell erstellen

Feature Engineering für NLP in Python

Rounak Banik

Data Scientist

Rückblick: Datenformat für ML-Algorithmen

Für jeden ML-Algorithmus gilt:

  • Daten müssen tabellarisch sein
  • Trainingsfeatures müssen numerisch sein
Feature Engineering für NLP in Python

Bag-of-Words-Modell

  • Wort-Tokens extrahieren
  • Häufigkeit der Wort-Tokens berechnen
  • Aus diesen Häufigkeiten und dem Korpus-Vokabular einen Wortvektor bilden
Feature Engineering für NLP in Python

Beispiel: Bag-of-Words-Modell

Korpus

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

Beispiel: Bag-of-Words-Modell

Vokabulara, 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 für NLP in Python

Textvorverarbeitung

  • Lions, lionlion
  • The, thethe
  • Keine Satzzeichen
  • Keine Stoppwörter
  • Führt zu kleinerem Vokabular
  • Weniger Dimensionen verbessern die Performance
Feature Engineering für NLP in Python

Bag-of-Words mit 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 für NLP in Python

Bag-of-Words mit sklearn

# Import CountVectorizer
from sklearn.feature_extraction.text import CountVectorizer

# CountVectorizer-Objekt erstellen vectorizer = CountVectorizer()
# Matrix der Wortvektoren erzeugen 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 für NLP in Python

Lass uns üben!

Feature Engineering für NLP in Python

Preparing Video For Download...