What does Keras Tokenizer num_words specify?

Viewed 4722

Given this piece of code:

from tensorflow.keras.preprocessing.text import Tokenizer

sentences = [
    'i love my dog',
    'I, love my cat',
    'You love my dog!'
]

tokenizer = Tokenizer(num_words = 1)
tokenizer.fit_on_texts(sentences)
word_index = tokenizer.word_index
print(word_index)

whether num_words=1 or num_words=100, I get the same output when I run this cell on my jupyter notebook, and I can't seem to understand what difference it makes in tokenization.

{'love': 1, 'my': 2, 'i': 3, 'dog': 4, 'cat': 5, 'you': 6}

1 Answers

word_index it's simply a mapping of words to ids for the entire text corpus passed whatever the num_words is

the difference is evident in the usage. for example, if we call texts_to_sequences

sentences = [
    'i love my dog',
    'I, love my cat',
    'You love my dog!'
]

tokenizer = Tokenizer(num_words = 1+1)
tokenizer.fit_on_texts(sentences)
tokenizer.texts_to_sequences(sentences) # [[1], [1], [1]]

only the love id is returned because the most frequent word

instead

sentences = [
    'i love my dog',
    'I, love my cat',
    'You love my dog!'
]

tokenizer = Tokenizer(num_words = 100+1)
tokenizer.fit_on_texts(sentences)
tokenizer.texts_to_sequences(sentences) # [[3, 1, 2, 4], [3, 1, 2, 5], [6, 1, 2, 4]]

the ids of the most 100 frequent words is returned

Related