Kaggle's NLP: Text Classification
Text Classification with SpaCy
A common task in NLP is text classification. This is "classification" in the conventional machine learning sense, and it is applied to text. Examples include spam detection, sentiment analysis, and tagging customer queries.
In this tutorial, you'll learn text classification with spaCy. The classifier will detect spam messages, a common functionality in most email clients. Here is an overview of the data you'll use:
import pandas as pd
# Loading the spam data
# ham is the label for non-spam messages
spam = pd.read_csv('../input/nlp-course/spam.csv')
Bag of Words
Machine learning models don't learn from raw text data. Instead, you need to convert the text to something numeric.
The simplest common representation is a variation of one-hot encoding. You represent each document as a vector of term frequencies for each term in the vocabulary. The vocabulary is built from all the tokens (terms) in the corpus (the collection of documents).
As an example, take the sentences "Tea is life. Tea is love." and "Tea is healthy, calming, and delicious." as our corpus. The vocabulary then is {"tea", "is", "life", "love", "healthy", "calming", "and", "delicious"} (ignoring punctuation).
For each document, count up how many times a term occurs, and place that count in the appropriate element of a vector. The first sentence has "tea" twice and that is the first position in our vocabulary, so we put the number 2 in the first element of the vector. Our sentences as vectors then look like
v1=[ 2 2 1 1 0 0 0 0 ]
v2=[ 1 1 0 0 1 1 1 1]
This is called the bag of words representation. You can see that documents with similar terms will have similar vectors. Vocabularies frequently have tens of thousands of terms, so these vectors can be very large.
Another common representation is TF-IDF (Term Frequency - Inverse Document Frequency). TF-IDF is similar to bag of words except that each term count is scaled by the term's frequency in the corpus. Using TF-IDF can potentially improve your models. You won't need it here. Feel free to look it up though!
Building a Bag of Words model
Once you have your documents in a bag of words representation, you can use those vectors as input to any machine learning model. spaCy handles the bag of words conversion and building a simple linear model for you with the TextCategorizer class.
The TextCategorizer is a spaCy pipe. Pipes are classes for processing and transforming tokens. When you create a spaCy model with nlp = spacy.load('en_core_web_sm'), there are default pipes that perform part of speech tagging, entity recognition, and other transformations. When you run text through a model doc = nlp("Some text here"), the output of the pipes are attached to the tokens in the doc object. The lemmas for token.lemma_ come from one of these pipes.
You can remove or add pipes to models. What we'll do here is create an empty model without any pipes (other than a tokenizer, since all models always have a tokenizer). Then, we'll create a TextCategorizer pipe and add it to the empty model.
import spacy
nlp = spacy.blank("en")
# Create the TextCategorizer with exclusive classes and "bow" architecture
textcat = nlp.create_pipe(
"textcat",
config={
"exclusive_classes": True,
"architecture": "bow"})
# Add the TextCategorizer to the empty model
nlp.add_pipe(textcat)
Since the classes are either ham or spam, we set "exclusive_classes" to True. We've also configured it with the bag of words ("bow") architecture. spaCy provides a convolutional neural network architecture as well, but it's more complex than you need for now.
Next we'll add the labels to the model. Here "ham" are for the real messages, "spam" are spam messages.
# Add labels to text classifier
textcat.add_label("ham")
textcat.add_label("spam")
Training a Text Categorizer Model
Next, you'll convert the labels in the data to the form TextCategorizer requires. For each document, you'll create a dictionary of boolean values for each class.
For example, if a text is "ham", we need a dictionary {'ham': True, 'spam': False}. The model is looking for these labels inside another dictionary with the key 'cats'.
train_texts = spam['text'].values
train_labels = [{'cats': {'ham': label == 'ham',
'spam': label == 'spam'}}
for label in spam['label']]
Then we combine the texts and labels into a single list.
train_data = list(zip(train_texts, train_labels))
train_data[:3]
[('Go until jurong point, crazy.. Available only in bugis n great world la e buffet... Cine there got amore wat...',
{'cats': {'ham': True, 'spam': False}}),
('Ok lar... Joking wif u oni...', {'cats': {'ham': True, 'spam': False}}),
("Free entry in 2 a wkly comp to win FA Cup final tkts 21st May 2005. Text FA to 87121 to receive entry question(std txt rate)T&C's apply 08452810075over18's",
{'cats': {'ham': False, 'spam': True}})]
Now you are ready to train the model. First, create an optimizer using nlp.begin_training(). spaCy uses this optimizer to update the model. In general it's more efficient to train models in small batches. spaCy provides the minibatch function that returns a generator yielding minibatches for training. Finally, the minibatches are split into texts and labels, then used with nlp.update to update the model's parameters.
from spacy.util import minibatch
spacy.util.fix_random_seed(1)
optimizer = nlp.begin_training()
# Create the batch generator with batch size = 8
batches = minibatch(train_data, size=8)
# Iterate through minibatches
for batch in batches:
# Each batch is a list of (text, label) but we need to
# send separate lists for texts and labels to update().
# This is a quick way to split a list of tuples into lists
texts, labels = zip(*batch)
nlp.update(texts, labels, sgd=optimizer)
This is just one training loop (or epoch) through the data. The model will typically need multiple epochs. Use another loop for more epochs, and optionally re-shuffle the training data at the begining of each loop.
random.seed(1)
spacy.util.fix_random_seed(1)
optimizer = nlp.begin_training()
losses = {}
for epoch in range(10):
random.shuffle(train_data)
# Create the batch generator with batch size = 8
batches = minibatch(train_data, size=8)
# Iterate through minibatches
for batch in batches:
texts, labels = zip(*batch)
nlp.update(texts, labels, sgd=optimizer, losses=losses)
print(losses)
{'textcat': 0.43349911164852983}
{'textcat': 0.6496019514395925}
{'textcat': 0.7863673793854753}
{'textcat': 0.873747565239956}
{'textcat': 0.9302242411678097}
{'textcat': 0.967743759023069}
{'textcat': 0.9961505934359941}
{'textcat': 1.0150542123599622}
{'textcat': 1.029843157208506}
{'textcat': 1.0401488806910077}
Making Predictions
Now that you have a trained model, you can make predictions with the predict() method. The input text needs to be tokenized with nlp.tokenizer. Then you pass the tokens to the predict method which returns scores. The scores are the probability the input text belongs to the classes.
texts = ["Are you ready for the tea party????? It's gonna be wild",
"URGENT Reply to this message for GUARANTEED FREE TEA" ]
docs = [nlp.tokenizer(text) for text in texts]
# Use textcat to get the scores for each doc
textcat = nlp.get_pipe('textcat')
scores, _ = textcat.predict(docs)
print(scores)
[[9.9994671e-01 5.3249827e-05]
[1.1798984e-02 9.8820102e-01]]
The scores are used to predict a single class or label by choosing the label with the highest probability. You get the index of the highest probability with scores.argmax, then use the index to get the label string from textcat.labels.
# From the scores, find the label with the highest score/probability
predicted_labels = scores.argmax(axis=1)
print([textcat.labels[label] for label in predicted_labels])
['ham', 'spam']
Evaluating the model is straightforward once you have the predictions. To measure the accuracy, calculate how many correct predictions are made on some test data, divided by the total number of predictions.
Let us now apply what we have learned to predict the sentiment of Yelp reviews.
sentiment analysis of Yelp reviews
Natural Language Classification
The restaurant's menu includes an email address where visitors can give feedback about their food.
The manager wants you to create a tool that automatically sends him all the negative reviews so he can fix them, while automatically sending all the positive reviews to the owner, so the manager can ask for a raise.
You will first build a model to distinguish positive reviews from negative reviews using Yelp reviews because these reviews include a rating with each review. Your data consists of the text body of each review along with the star rating. Ratings with 1-2 stars count as "negative", and ratings with 4-5 stars are "positive". Ratings with 3 stars are "neutral" and have been dropped from the data.
Review Data and Create the model
Moving forward with your plan, you'll need to load the data. Here's some basic code to load data and split it into a training and validation set. Run this code.
import pandas as pd
def load_data(csv_file, split=0.9):
data = pd.read_csv(csv_file)
# Shuffle data
train_data = data.sample(frac=1, random_state=7)
texts = train_data.text.values
labels = [{"POSITIVE": bool(y), "NEGATIVE": not bool(y)}
for y in train_data.sentiment.values]
split = int(len(train_data) * split)
train_labels = [{"cats": labels} for labels in labels[:split]]
val_labels = [{"cats": labels} for labels in labels[split:]]
return texts[:split], train_labels, texts[split:], val_labels
train_texts, train_labels, val_texts, val_labels = load_data('../input/nlp-course/yelp_ratings.csv')
You will use this training data to build a model. The code to build the model is the same as what you saw in the tutorial. So that is copied below for you.
But because your data is different, there are two lines in the modeling code cell that you'll need to change. Can you figure out what they are?
import spacy
# Create an empty model
nlp_baseline = spacy.blank("en")
# Create the TextCategorizer with exclusive classes and "bow" architecture
textcat = nlp_baseline.create_pipe(
"textcat",
config={
"exclusive_classes": True,
"architecture": "bow"})
# Add the TextCategorizer to the empty model
nlp_baseline.add_pipe(textcat)
# Add labels to text classifier
# Add labels to text classifier
textcat.add_label("NEGATIVE")
textcat.add_label("POSITIVE")
Train Function
Implement a function train that updates a model with training data. We'll also log the losses using wandb which will enable us to track and compare the model performance.
from spacy.util import minibatch
import random
def train(model, train_data, optimizer, batch_size=8):
losses = {}
random.shuffle(train_data)
batches = minibatch(train_data, size=batch_size)
for batch in batches:
texts, labels = zip(*batch)
model.update(texts, labels, sgd=optimizer, losses=losses)
wandb.log(losses)
return losses
Making Predictions
Implement a function predict that predicts the sentiment of text examples.
First, tokenize the texts using nlp.tokenizer().
Then, pass those docs to the TextCategorizer which you can get from nlp.get_pipe().
Use the textcat.predict() method to get scores for each document, then choose the class with the highest score (probability) as the predicted class.
def predict(nlp_baseline, texts):
# Use the tokenizer to tokenize each input text example
docs = [nlp_baseline.tokenizer(text) for text in texts]
# Use textcat to get the scores for each doc
textcat = nlp_baseline.get_pipe('textcat')
scores, _ = textcat.predict(docs)
# From the scores, find the class with the highest score/probability
predicted_class = scores.argmax(axis=1)
return predicted_class
Evaluate The Model
Implement a function that evaluates a TextCategorizer model. This function evaluate takes a model along with texts and labels. It returns the accuracy of the model, which is the number of correct predictions divided by all predictions.
import wandb
def evaluate(model, texts, labels):
# Get predictions from textcat model (using your predict method)
predicted_class = predict(model,texts)
# From labels, get the true class as a list of integers (POSITIVE -> 1, NEGATIVE -> 0)
true_class = [int(each['cats']['POSITIVE']) for each in labels]
# A boolean or int array indicating correct predictions
correct_predictions = predicted_class == true_class
# The accuracy, number of correct predictions divided by all predictions
accuracy = correct_predictions.mean()
wandb.log({"accuracy":accuracy})
return accuracy
Let us now train 3 different model architectures and compare the performance using wandb.
- Let's first train the Baseline model that we have already defined
n_iters = 10
for i in range(n_iters):
losses = train(nlp_baseline, train_data, optimizer)
accuracy = evaluate(nlp_baseline, val_texts, val_labels)
print(f"Loss: {losses['textcat']:.3f} \t Accuracy: {accuracy:.3f}")
- The model with ensemble architecture
textcat = nlp_cnn.create_pipe(
"textcat",
config={
"exclusive_classes": True,
"architecture": "ensemble"})
- The model with
simple_cnnarchitecture
textcat = nlp_cnn.create_pipe(
"textcat",
config={
"exclusive_classes": True,
"architecture": "simple_cnn"})
Visualizations
Let us now look at the wandb dashboard for this project to see how these 3 models compare.