Construindo um modelo bag of words

Feature Engineering para NLP em Python

Rounak Banik

Data Scientist

Revisão do formato de dados para algoritmos de ML

Para qualquer algoritmo de ML,

  • Os dados devem estar em formato tabular
  • As features de treino devem ser numéricas
Feature Engineering para NLP em Python

Modelo bag of words

  • Extrair tokens de palavras
  • Calcular a frequência dos tokens
  • Construir um vetor de palavras a partir dessas frequências e do vocabulário do corpus
Feature Engineering para NLP em Python

Exemplo de modelo 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 para NLP em Python

Exemplo de modelo bag of words

Vocabulário → 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 para NLP em Python

Pré-processamento de texto

  • Lions, lion → lion
  • The, the → the
  • Sem pontuação
  • Sem stopwords
  • Leva a vocabulários menores
  • Reduzir dimensões ajuda no desempenho
Feature Engineering para NLP em Python

Modelo bag of words com 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 para NLP em Python

Modelo bag of words com sklearn

# Import CountVectorizer
from sklearn.feature_extraction.text import CountVectorizer

# Criar o objeto CountVectorizer vectorizer = CountVectorizer()
# Gerar a matriz de vetores de palavras 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 para NLP em Python

Vamos praticar!

Feature Engineering para NLP em Python

Preparing Video For Download...