Construirea unui model bag of words

Ingineria caracteristicilor pentru NLP în Python

Rounak Banik

Data Scientist

Formatul datelor pentru algoritmii ML

Pentru orice algoritm ML,

  • Datele trebuie să fie în format tabelar
  • Caracteristicile de antrenare trebuie să fie numerice
Ingineria caracteristicilor pentru NLP în Python

Modelul bag of words

  • Extragerea tokenilor de cuvinte
  • Calcularea frecvenței tokenilor
  • Construirea unui vector de cuvinte din frecvențe și vocabularul corpusului
Ingineria caracteristicilor pentru NLP în Python

Exemplu de model bag of words

Corpus

"The lion is the king of the jungle"
"Lions have lifespans of a decade"
"The lion is an endangered species"
Ingineria caracteristicilor pentru NLP în Python

Exemplu de model bag of words

Vocabulara, 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]
Ingineria caracteristicilor pentru NLP în Python

Preprocesarea textului

  • Lions, lionlion
  • The, thethe
  • Fără semne de punctuație
  • Fără cuvinte de oprire
  • Conduce la vocabulare mai reduse
  • Reducerea dimensiunilor îmbunătățește performanța
Ingineria caracteristicilor pentru NLP în Python

Model bag of words cu sklearn

corpus = pd.Series([
    'The lion is the king of the jungle',
    'Lions have lifespans of a decade',
    'The lion is an endangered species'
])
Ingineria caracteristicilor pentru NLP în Python

Model bag of words cu 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)
Ingineria caracteristicilor pentru NLP în Python

Să exersăm!

Ingineria caracteristicilor pentru NLP în Python

Preparing Video For Download...