Module 18 · Natural language processing · Lesson 60 of 66
Turn text into numbers
Clean text, count words into a bag of words, weight them with TF-IDF, and classify with naive Bayes.
In this lesson · about 30 minutes
- Remove punctuation and stop words from text
- Build a bag of words with CountVectorizer and weight it with TF-IDF
- Train a MultinomialNB text classifier inside a Pipeline
Models need numbers, but a lot of data is text: reviews, emails, support tickets. Natural language processing (NLP) covers the ways to turn text into numbers a model can use. The classic recipe:
- Clean the text: drop punctuation and very common words like "the" and "is" (stop words) that say little about meaning.
- Count: list every word that appears anywhere (the vocabulary) and represent each document as how many times it uses each word. This is a bag of words: word order is lost, but the counts carry a lot of meaning.
- Weight with TF-IDF (term frequency times inverse document frequency): a word counts more when it's frequent in this document but rare across all documents.
- Classify, often with naive Bayes, a fast model that works well on word counts.
We'll work with Yelp reviews: the text, the star rating (1 to 5), and how many people voted the review cool, useful or funny. This is a 3,000-review sample.
Cleaning text
Python's string.punctuation lists the punctuation characters. scikit-learn includes a list of about 300 English stop words, ENGLISH_STOP_WORDS. (The course notebook uses NLTK's list, which needs a separate download; the idea is the same.)
Exercise
A text cleaner
Write text_process(text): remove every punctuation character, split into words, and return the list of words whose lowercase form isn't in ENGLISH_STOP_WORDS. End by applying it to the first five reviews: yelp['text'].head().apply(text_process).
Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
yelp = pd.read_csv('yelp.csv')
import string
from sklearn.feature_extraction.text import ENGLISH_STOP_WORDSBag of words
CountVectorizer learns the vocabulary and counts words. Pass it your cleaner with analyzer=text_process. The result is a sparse matrix: one row per review, one column per word, and almost all zeros, so it only stores the non-zero counts.
Exercise
Weight the words
Fit a TfidfTransformer called tfidf_transformer on review_bow and transform it into review_tfidf. End with the IDF weight of the word 'pizza': tfidf_transformer.idf_[bow_transformer.vocabulary_['pizza']].
Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
yelp = pd.read_csv('yelp.csv')
import string
from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
def text_process(text):
"""Remove punctuation and stop words; return a list of the remaining words."""
nopunc = ''.join(char for char in text if char not in string.punctuation)
return [word for word in nopunc.split() if word.lower() not in ENGLISH_STOP_WORDS]
from sklearn.feature_extraction.text import CountVectorizer
bow_transformer = CountVectorizer(analyzer=text_process).fit(yelp['text'])
review_bow = bow_transformer.transform(yelp['text'])A pipeline
A Pipeline chains the steps into one model: give it raw text and it cleans, counts, weights and classifies. You fit and predict with it like any model, and you can't accidentally forget a step on the test data.
Exercises solved: 0 of 2
Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.