Classifying Tweets with Amazon ML
Tags: machinelearning, datascience, amazonml, aws
Published: 2017-01-30 01:32:37

---
title: Classifying Tweets with Amazon ML
published: true
description: Amazon ML is extremely easy to use. Itâ€™s a great way to easily compute basic ML models, and quickly integrate your models into application layer code.
cover_image: http://i.imgur.com/NiADR6w.png
tags: machinelearning, datascience, AmazonML, AWS
---

## Preface

I recently watched an awesome [video overview/demo](https://www.youtube.com/watch?v=GRRX9amYsyM) of one of AWSâ€™s newer servicesâ€Šâ€”â€ŠAmazon ML. If you have ~50 minutes on hand to watch the above video and follow along I highly suggest it, if not read the rest of my blog post for a much briefer summary.

So what is Amazon ML?

>Amazon Machine Learning is a service that makes it easy for developers of all skill levels to use machine learning technology. Amazon Machine Learning provides visualization tools and wizards that guide you through the process of creating machine learning (ML) models without having to learn complex ML algorithms and technology. Once your models are ready, Amazon Machine Learning makes it easy to obtain predictions for your application using simple APIs, without having to implement custom prediction generation code, or manage any infrastructure.

In other words, itâ€™s **machine learning as a service**. For those familiar with machine learning, Amazonâ€™s service doesnâ€™t yet provide any sort of deep learning models, only regression and classification models. Nonetheless, you can do some fairly powerful stuff with these _shallow learning_ models.

## Overview

In the video linked above the speaker goes through an example in which he builds a model to **automatically classify tweets directed at AWS customer support as actionable or not actionable**. You can probably imagine a few different use cases for a model like this, one being a great way to save your customer support agents time filtering through garbage social media data to find actual customer issues/problems. Iâ€™ll go through the same example with my own companyâ€™s ([Weebly](https://www.weebly.com)) twitter data below.

The entire process of creating our ML model can be boiled down to 4 simple steps:
- Collect our Data
- Classify Our Data
- Feed our classified data to Amazonâ€™s ML engine
- Test it out!

## Collecting ourÂ Data

First we need some actual data to work with. Since weâ€™ll be using twitter data, we can take advantage of the Twitter API to get a large subset of tweets that meet our requirement (i.e. tweets directed @weebly). This means youâ€™ll have to register an [developer application](https://apps.twitter.com/) on twitter to get your relevant API keys and tokens. Once you do that you can start fetching the data you need from twitter. Below is a little ruby script to get all the tweets we care about and save them to a CSV.

```
# Twitter client gem - https://github.com/sferik/twitter
client = Twitter::REST::Client.new do |config|
  config.consumer_key        = "API_KEY"
  config.consumer_secret     = "SECRET"
  config.access_token        = "ACCESS_TOKEN"
  config.access_token_secret = "ACCESS_TOKEN_SECRET"
end

CSV.open("weebly_tweets", "wb") do |csv|
  csv << ["username", "tweet"] # first row
  client.search("@weebly", lang: "en").collect do |tweet|
    csv << [tweet.user.screen_name, tweet.text]
  end
end
```

Awesome, now we have a CSV with thousands of rows of tweets. Time for the classification portion.

## Data Classification

Now that we have all our tweets in a CSV we need to classify them as actionable or not. One way we could do this is to create a third column in our CSV and manually go through all the tweets and classify them ourselvesâ€¦ that sounds pretty awful though. Fortunately Amazon has another pretty handy service called [Amazon Mechanical Turk](https://www.mturk.com/mturk/welcome). Using this service we can hire people to classify these tweets for us at a price we determine (often as low as a couple of cents per tweet). You can choose how many different people should be hired to classify your tweets, at what cost, and various other configurations. Below are some screenshots from the Mechanical Turk interface:

![](https://cdn-images-1.medium.com/max/1600/1*UYXyOinMjlnafVBlUTEvhQ.png)
_configure HIT (Human Intelligence Task)_

![](https://cdn-images-1.medium.com/max/1600/1*1V_XntCYc8vVEUhue2ku8Q.png)
_HIT instructions_

One important thing thatâ€™s easy to forget when creating machine learning models is making sure you have a good **clean data set**. Iâ€™m fairly new to creating ML models and in pretty much every instance Iâ€™ve worked on a model I end up constantly going back to the original data set and re running the model because of some data cleaning I did after the fact. Some early filtering on your data could end up in big wins down the line with your models performance, and save you lots of time. One exampleâ€Šâ€”â€Šthe first time I fetched all this twitter data I noticed lots of tweets in Chinese. Unless our customer support agents speak Chinese this data will only pollute our model. Another example is that I noticed lots of tweets that were automatically generated by Weeblyâ€™s Blog Platformâ€™s â€œshareâ€ featureâ€Šâ€”â€Šthese could be easily filtered out of data set by a simple check for certain text (â€œblog post shared via @weeblyâ€). Our model could easily learn to classify these appropriately but we could save time calculating our model by filtering out these tweets beforehand, and more importantly we could save money if we are paying a third party classification service to classify our data.

## Creating OurÂ Model

Once weâ€™ve got all our data classified and an additional column in our csv with the labeled data, we can begin to actually create our model. As of the date Iâ€™m writing this, Amazon ML models need to pull data from either S3 or RedShift. I created a new s3 bucket quickly and placed by `weebly_tweets.csv` there.

From the Amazon ML [console](https://console.aws.amazon.com/machinelearning) you can select â€œCreate new Model and Datasourceâ€. From there we can follow the fairly straightforward steps in creating our model. Noteâ€Šâ€”â€Šwe can do all of the below via Amazonâ€™s API, but for clarity and easier visualization Iâ€™ll use the console.

![](https://cdn-images-1.medium.com/max/1600/1*17VJJYQv4RJTC8DXIwG3tw.png)

In this first step we simply enter the location of our data and name this new Datasource. The steps after this will just have you confirm your columns and their data types, as well as identify the target column (the output). After creating our Datasource weâ€™ll finally get to the point of actually being able to create our model.

![](https://cdn-images-1.medium.com/max/1600/1*Zj4iytVUbcUw_e4Y_4ASaw.png)

The screenshot above is the initial screen youâ€™ll see when creating a model. Choosing the default training and evaluation settings basically means you let Amazon configure everything about your model. If you choose custom you can change things like your regularization parameter, the training data vs evaluation data split, whether to randomly or sequentially choose training data, and more. The first time around I would suggest choosing Default and letting Amazon configure things for youâ€Šâ€”â€Šif you arenâ€™t happy with your results then you can start trying to work on some customizations.

Once you finish creating your model- **boom!** Amazon will start putting itâ€™s servers to work on training your model. Depending on how much data you feed it, this step can take awhile. Running binary classification on a couple thousand tweets took about ~7 minutes or so. Once itâ€™s done we can check out how our model performed.

![](https://cdn-images-1.medium.com/max/1600/1*b_jR6buuQYMw5EpRqq2Z5w.png)

Amazon will give you a nice little chart explaining your models performance on the evaluation data set. As you can see from the screenshot above, our modeled classified tweets as actionable at an 88% correct rateâ€Šâ€”â€Šthatâ€™s pretty cool. From this model performance screen you can also modify your modelâ€™s threshold to give you more or less false positives/negatives. In the case of actionable tweets, I figured itâ€™s better to have more false positives (a tweet is marked actionable when itâ€™s not), rather than false negatives (a tweet is marked not actionable and it was), so I modified my model to err on the side of false positives.

## Testing our Model/Where do we go fromÂ here?

Cool weâ€™ve got a model that works wellâ€¦ now what? For starters we can try out real time predictions right in the Amazon console.

![](https://cdn-images-1.medium.com/max/1600/1*fjYXhyiwKGioYLHCPs_dng.png)

In this instance (above) I tested _â€œ@weebly how do I fix my website?â€_ and correctly got a prediction of actionable (1 is actionable, 0 is not). In the â€œpredictedScoresâ€ blob you can get a closer look at how the model actually scored your data. The closer to 1 our score was the more confident the model was that it was actionable, and same for zero.

![](https://cdn-images-1.medium.com/max/1600/1*8BXTx00UUgtmj6MnPA1uMA.png)

As you can see in this example (_â€œ@weebly I love dogs!â€_) the model very confidently predicted that this is not an actionable tweet.

We can also interact with this model via Amazons API (maybe will save this for a separate post) so itâ€™s actually useful in a production environment.

## Conclusion

Amazon ML is extremely easy to use. Itâ€™s still in itâ€™s infancy so the amount of customization and insight into your model you have is still little compared to when using services like [tensorflow](https://www.tensorflow.org/) or [scikit-learn](http://scikit-learn.org/stable/). Overall, itâ€™s a great way to easily compute basic ML models, and quickly integrate your models into application layer code.