Costruire un modello bag-of-words

Feature Engineering per NLP in Python

Rounak Banik

Data Scientist

Formato dei dati per gli algoritmi di ML: riepilogo

Per qualsiasi algoritmo di Machine Learning,

  • I dati devono essere in forma tabellare
  • Le feature di training devono essere numeriche
Feature Engineering per NLP in Python

Modello bag-of-words

  • Estrai i token di parola
  • Calcola la frequenza dei token
  • Costruisci un vettore di parole da frequenze e vocabolario del corpus
Feature Engineering per NLP in Python

Esempio di modello bag-of-words

Corpus

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

Esempio di modello bag-of-words

Vocabolario → 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]
Feature Engineering per NLP in Python

Preprocessing del testo

  • Lions, lion → lion
  • The, the → the
  • Niente punteggiatura
  • Niente stopword
  • Vocabolari più piccoli
  • Ridurre le dimensioni aiuta le prestazioni
Feature Engineering per NLP in Python

Modello bag-of-words con 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 per NLP in Python

Modello bag-of-words con sklearn

# Import CountVectorizer
from sklearn.feature_extraction.text import CountVectorizer

# Crea l'oggetto CountVectorizer vectorizer = CountVectorizer()
# Genera la matrice dei vettori di parole 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 per NLP in Python

Esercitiamoci!

Feature Engineering per NLP in Python

Preparing Video For Download...