Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/Who's Tweeting_ Trump or Trudeau_/notebook.ipynb
Views: 1229
1. Tweet classification: Trump vs. Trudeau
So you think you can classify text? How about tweets? In this notebook, we'll take a dive into the world of social media text classification by investigating how to properly classify tweets from two prominent North American politicians: Donald Trump and Justin Trudeau.
Photo Credit: Executive Office of the President of the United States
Tweets pose specific problems to NLP, including the fact they are shorter texts. There are also plenty of platform-specific conventions to give you hassles: mentions, #hashtags, emoji, links and short-hand phrases (ikr?). Can we overcome those challenges and build a useful classifier for these two tweeters? Yes! Let's get started.
To begin, we will import all the tools we need from scikit-learn. We will need to properly vectorize our data (CountVectorizer
and TfidfVectorizer
). And we will also want to import some models, including MultinomialNB
from the naive_bayes
module, LinearSVC
from the svm
module and PassiveAggressiveClassifier
from the linear_model
module. Finally, we'll need sklearn.metrics
and train_test_split
and GridSearchCV
from the model_selection
module to evaluate and optimize our model.
2. Transforming our collected data
To begin, let's start with a corpus of tweets which were collected in November 2017. They are available in CSV format. We'll use a Pandas DataFrame to help import the data and pass it to scikit-learn for further processing.
Since the data has been collected via the Twitter API and not split into test and training sets, we'll need to do this. Let's use train_test_split()
with random_state=53
and a test size of 0.33, just as we did in the DataCamp course. This will ensure we have enough test data and we'll get the same results no matter where or when we run this code.
3. Vectorize the tweets
We have the training and testing data all set up, but we need to create vectorized representations of the tweets in order to apply machine learning.
To do so, we will utilize the CountVectorizer
and TfidfVectorizer
classes which we will first need to fit to the data.
Once this is complete, we can start modeling with the new vectorized tweets!
4. Training a multinomial naive Bayes model
Now that we have the data in vectorized form, we can train the first model. Investigate using the Multinomial Naive Bayes model with both the CountVectorizer
and TfidfVectorizer
data. Which do will perform better? How come?
To assess the accuracies, we will print the test sets accuracy scores for both models.
5. Evaluating our model using a confusion matrix
We see that the TF-IDF model performs better than the count-based approach. Based on what we know from the NLP fundamentals course, why might that be? We know that TF-IDF allows unique tokens to have a greater weight - perhaps tweeters are using specific important words that identify them! Let's continue the investigation.
For classification tasks, an accuracy score doesn't tell the whole picture. A better evaluation can be made if we look at the confusion matrix, which shows the number correct and incorrect classifications based on each class. We can use the metrics, True Positives, False Positives, False Negatives, and True Negatives, to determine how well the model performed on a given class. How many times was Trump misclassified as Trudeau?
6. Trying out another classifier: Linear SVC
So the Bayesian model only has one prediction difference between the TF-IDF and count vectorizers -- fairly impressive! Interestingly, there is some confusion when the predicted label is Trump but the actual tweeter is Trudeau. If we were going to use this model, we would want to investigate what tokens are causing the confusion in order to improve the model.
Now that we've seen what the Bayesian model can do, how about trying a different approach? LinearSVC is another popular choice for text classification. Let's see if using it with the TF-IDF vectors improves the accuracy of the classifier!
7. Introspecting our top model
Wow, the LinearSVC model is even better than the Multinomial Bayesian one. Nice work! Via the confusion matrix we can see that, although there is still some confusion where Trudeau's tweets are classified as Trump's, the False Positive rate is better than the previous model. So, we have a performant model, right?
We might be able to continue tweaking and improving all of the previous models by learning more about parameter optimization or applying some better preprocessing of the tweets.
Now let's see what the model has learned. Using the LinearSVC Classifier with two classes (Trump and Trudeau) we can sort the features (tokens), by their weight and see the most important tokens for both Trump and Trudeau. What are the most Trump-like or Trudeau-like words? Did the model learn something useful to distinguish between these two men?
8. Bonus: can you write a Trump or Trudeau tweet?
So, what did our model learn? It seems like it learned that Trudeau tweets in French!
I challenge you to write your own tweet using the knowledge gained to trick the model! Use the printed list or plot above to make some inferences about what words will classify your text as Trump or Trudeau. Can you fool the model into thinking you are Trump or Trudeau?
If you can write French, feel free to make your Trudeau-impersonation tweet in French! As you may have noticed, these French words are common words, or, "stop words". You could remove both English and French stop words from the tweets as a preprocessing step, but that might decrease the accuracy of the model because Trudeau is the only French-speaker in the group. If you had a dataset with more than one French speaker, this would be a useful preprocessing step.
Future work on this dataset could involve:
- Add extra preprocessing (such as removing URLs or French stop words) and see the effects
- Use GridSearchCV to improve both your Bayesian and LinearSVC models by finding the optimal parameters
- Introspect your Bayesian model to determine what words are more Trump- or Trudeau- like
- Add more recent tweets to your dataset using tweepy and retrain
Good luck writing your impersonation tweets -- feel free to share them on Twitter!