Bygga en bag of words-modell

Funktionsutveckling för NLP i Python

Rounak Banik

Data Scientist

Dataformat för ML-algoritmer

För alla ML-algoritmer,

  • Data måste vara i tabellform
  • Träningssärdrag måste vara numeriska
Funktionsutveckling för NLP i Python

Bag of words-modellen

  • Extrahera ordtoken
  • Beräkna frekvensen av ordtoken
  • Konstruera en ordvektor utifrån dessa frekvenser och korpusens vokabulär
Funktionsutveckling för NLP i Python

Exempel på bag of words-modellen

Korpus

"The lion is the king of the jungle"
"Lions have lifespans of a decade"
"The lion is an endangered species"
Funktionsutveckling för NLP i Python

Exempel på bag of words-modellen

Vokabulära, 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]
Funktionsutveckling för NLP i Python

Textförbehandling

  • Lions, lionlion
  • The, thethe
  • Inga skiljetecken
  • Inga stoppord
  • Ger ett mindre vokabulär
  • Färre dimensioner förbättrar prestandan
Funktionsutveckling för NLP i Python

Bag of words-modell med sklearn

corpus = pd.Series([
    'The lion is the king of the jungle',
    'Lions have lifespans of a decade',
    'The lion is an endangered species'
])
Funktionsutveckling för NLP i Python

Bag of words-modell med 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)
Funktionsutveckling för NLP i Python

Nu kör vi en övning!

Funktionsutveckling för NLP i Python

Preparing Video For Download...