Sklearn: adding lemmatizer to CountVectorizer

Rens picture Rens · Nov 21, 2017 · Viewed 14.9k times · Source

I added lemmatization to my countvectorizer, as explained on this Sklearn page.

from nltk import word_tokenize          
from nltk.stem import WordNetLemmatizer 
class LemmaTokenizer(object):
    def __init__(self):
        self.wnl = WordNetLemmatizer()
    def __call__(self, articles):
        return [self.wnl.lemmatize(t) for t in word_tokenize(articles)]

tf_vectorizer = CountVectorizer(tokenizer=LemmaTokenizer,
                       strip_accents = 'unicode',
                       stop_words = 'english',
                       lowercase = True,
                       token_pattern = r'\b[a-zA-Z]{3,}\b', # keeps words of 3 or more characters
                       max_df = 0.5,
                       min_df = 10)

However, when creating a dtm using fit_transform, I get the error below (of which I can't make sense). Before adding the lemmatization to my vectorizer, the dtm code always worked. I went deeper into the manual, and tried some things with the code, but couldn't find any solution.

dtm_tf = tf_vectorizer.fit_transform(articles)

Update:

After following @MaxU's advice below, the code run without error, however numbers and punctuation were not ommited from my output. I run individual tests to see which of the other functions after LemmaTokenizer() do and do not work. Here is the result:

strip_accents = 'unicode', # works
stop_words = 'english', # works
lowercase = True, # works
token_pattern = r'\b[a-zA-Z]{3,}\b', # does not work
max_df = 0.5, # works
min_df = 10 # works

Appearantly, it is just token_pattern which became inactive. Here is the updated and working code without token_pattern (I just needed to install the 'punkt' and 'wordnet' packages first):

from nltk import word_tokenize          
from nltk.stem import WordNetLemmatizer 
class LemmaTokenizer(object):
    def __init__(self):
        self.wnl = WordNetLemmatizer()
    def __call__(self, articles):
        return [self.wnl.lemmatize(t) for t in word_tokenize(articles)]

tf_vectorizer = CountVectorizer(tokenizer=LemmaTokenizer(),
                                strip_accents = 'unicode', # works 
                                stop_words = 'english', # works
                                lowercase = True, # works
                                max_df = 0.5, # works
                                min_df = 10) # works

For those who want to remove digits, punctuation and words of less than 3 characters (but have no idea how), here is one way that does it for me when working from Pandas dataframe

# when working from Pandas dataframe

df['TEXT'] = df['TEXT'].str.replace('\d+', '') # for digits
df['TEXT'] = df['TEXT'].str.replace(r'(\b\w{1,2}\b)', '') # for words
df['TEXT'] = df['TEXT'].str.replace('[^\w\s]', '') # for punctuation 

Answer

MaxU picture MaxU · Nov 22, 2017

It should be:

tf_vectorizer = CountVectorizer(tokenizer=LemmaTokenizer(),
# NOTE:                        ---------------------->  ^^

instead of:

tf_vectorizer = CountVectorizer(tokenizer=LemmaTokenizer,