• Stars
    star
    130
  • Rank 277,575 (Top 6 %)
  • Language
    Scala
  • License
    Apache License 2.0
  • Created over 8 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🌟 ✨ Analyze and visualize Twitter Sentiment on a world map using Spark MLlib

Twitter sentiment analysis with Spark MLlib and visualization

Introduction

Project to analyse and visualize sentiment of tweets in real-time on a world map using Apache Spark ecosystem [Spark MLlib + Spark Streaming].

At a very high level, this project encapsulates and covers each of the following broad topics:

  • Distributed Stream Processing » Apache Spark
  • Machine Learning » Naive Bayes Classifier [Apache Spark MLlib implementation]
  • Visualization » Sentiment visualization on a World map using Datamaps
  • DevOps » Docker Hub and Docker Image

For more details on this project and the code associated with it, please check this blogpost.
Also, a Docker Image is available on Docker Hub with the complete environment and dependencies installed and preconfigured.

Note:

I had actually written a blog post on my personal website with the code walkthru and explaining intricate details; but unfortunately I managed to corrupt my Octopress GitHub repo. 😧 😩 😡 So, till the time I salvage it, I thought of publishing it as GitHub wiki for the time being.

Visualization Demo and screenshots

Demo of visualization

Demo of visualization

Screenshots of visualization

Overview

Overview

Positive sentiment

Positive sentiment

Neutral sentiment

Neutral sentiment

Negative sentiment

Negative sentiment

Features

  • Apache Spark MLlib's implementation of Naive Bayes classifier is used for classifying the tweets in real-time.
  • Training is performed using 1.6 million tweet training data made available by Sentiment140.
  • Model created by Naive Bayes is applied in real-time to the tweets retrieved using Twitter Streaming API to determine the sentiment of each of the tweets.
  • We also compare this result with Stanford CoreNLP sentiment prediction.
  • Tweets are classified by both these approaches as:
    • Positive
    • Neutral
    • Negative
  • Please note all non-English tweets are classified as "neutral" as our training data consists of English language only tweets.
  • We analyze and process and consider only the tweets which have location and discard tweets without location info.
    • This is to facilitate the visualization based on the latitude, longitude info of the tweets.
  • Application can also save compressed raw tweets to the disk.
    • Please set SAVE_RAW_TWEETS flag to true in application.conf if you want to save / retain the raw tweets we retrieve from Twitter.
  • The result of the tweet is published to Redis which is subscribed by the front-end webapp for visualization.
  • Datamaps -- based on D3.js -- is used for visualization to display the tweet location on the world map with a pop up for more details on hover.
    • Hover over the bubbles to see the additional info of the tweets.
    • Visualization is fully responsive and scales well for any form factor. Works even on mobile.
    • App adjusts if a window is resized without impacting the UX or losing the data already on the screen.
    • Changes to the orientation [of a phone / tablet] does not have any impact on the app either.
  • This codebase has been updated with comments, where necessary.

Docker Image and Dockerfile

  • Docker image hosted on Docker Hub is available with the complete environment and dependencies installed.
  • Dockerfile and other supporting files are also available on GitHub.
  • For detailed info on this project, please check the blogpost.

Dependencies

Following is the complete list of languages and frameworks used and their significance in this project.

  1. OpenJDK 64-Bit v1.8.0_102 » Java for compiling and execution; the VM to be precise
  2. Scala v2.10.6 » basic infrastructure and Spark jobs
  3. SBT v0.13.12 » build script and uber jar creation
  4. Apache Spark v1.6.2
    • Spark Streaming » connecting to Twitter and streaming the tweets
    • Spark MLlib » creating a ML model and predicting the sentiment of tweets based on the text
    • Spark SQL » saving tweets [both raw and classified]
  5. Stanford CoreNLP v3.6.0 » alternative approach to find sentiment of tweets based on the text
  6. Redis » publishing classified tweets; subscribed by the front-end app to render the chart
  7. Datamaps » chart and visualization
  8. Python » run the flask app for rendering the front-end
  9. Flask » render the template for front-end

Also, please check build.sbt for more information on the various other dependencies of the project.

Prerequisites for successful execution

  • A machine with Docker installed and in which you can allocate at least the following [actually the more, the merrier] to the Docker-machine instance:
    • 2 GB RAM
    • 2 CPUs
    • 6 GB free disk space
  • We will need unfettered internet access for executing this project.
  • Twitter App OAuth credentials are mandatory.
    • These credentials are for retrieving tweets using Twitter Streaming API.
  • We will download ~1.5 GB of data with this image and SBT dependencies, etc and streaming tweets too.

Env Setup

If not already installed, please install Docker on your machine.

We will be using the accompanying Docker image created for this project.

Resources for the Docker machine

  • Stop docker-machine. docker-machine stop default
  • Launch VirtualBox and click on settings of default instance, which should be in Powered Off state.
  • Fix the settings as highlighted in the screenshots below.
    • Please note this is minimum required config; you might want to allocate more.
  • Increase RAM of the VM
    Docker Machine RAM
  • Increase # of CPUs of the VM
    Docker Machine CPU
  • Relaunch docker after modifying the settings. docker-machine start default
  • Any Docker image you create now will have 2 GB RAM and 2 CPUs allocated.
    • Or the resources you allocated earlier.

Execution

Run the Docker image

  • This step will pull the Docker image from Docker Hub and runs it.
    • If the image doesn't exist locally, the Docker Client will first fetch the image from the registry and then run the image.
    • After image boots up and completes the setup process, you will land into a bash shell waiting for your input.

docker run -ti -p 4040:4040 -p 8080:8080 -p 8081:8081 -p 9999:9999 -h spark --name=spark p7hb/p7hb-docker-mllib-twitter-sentiment:1.6.2

Please note:

  • root is the user we logged into.
  • spark is the container name.
  • spark is host name of this container.
    • This is very important as Spark Slaves are started using this host name as the master.
  • The container exposes ports 4040, 8080, 8081 for Spark Web UI console and 9999 for Twitter sentiment Visualization.

Twitter App OAuth credentials

  • The only manual intervention required in this project is setting up a Twitter App and updating OAuth credentials to connect to Twitter Streaming API. Please note that this is a critical step and without this, Spark will not be able to connect to Twitter or retrieve tweets with Twitter Streaming API and so, the visualization will be empty basically without any data.
  • Please check the application.conf and add your own values and complete the integration of Twitter API to your application by looking at your values from Twitter Developer Page.
    • If you did not create a Twitter App before, then please create a new Twitter App on Twitter Developer Page, where you will get all the required values of application.conf.

Execute Spark Streaming job for sentiment prediction

  • Please execute /root/exec_spark_jobs.sh in the console after updating the Twitter App OAuth credentials in application.conf.
    • This script first starts Spark services [Spark Master and Spark Slave] and then launches Spark jobs one after the other.
  • This might take sometime as SBT will initiate a download and setup of all the required packages from Maven Central Repo and Typesafe repo as required.

Visualization app

  • After a few minutes of launching the Spark jobs, point your browser on the host machine to http://192.168.99.100:9999/ to view the Twitter sentiment visualized on a world map.
  • When a tweet is classified, a small bubble appears on world map exactly showing the location from which that tweet originated from.
  • Hovering over a bubble displays the corresponding tweet's additional info:
  1. tweet handle
  2. tweet profile pic
  3. date tweet created
  4. text of the tweet
  5. sentiment predicted by MLlib
  6. sentiment as per Stanford CoreNLP

Further work and improvement areas

  • Visualization could be completely scrapped for something better and UX needs a lot of uplifting.
  • Use Spark package / wrapper for Stanford CoreNLP and reduce the boilerplate code further.
  • Current prediction accuracy is ~80%. Prediction accuracy needs to be rethinked about and probably a better dataset should be used for creating the model.
  • Update the project to Apache Spark v2.0.
    • Push out RDDs; hello DataFrames and Datasets!
    • And also use org.apache.spark.ml package.
    • Speed gains too!
  • Also processing and predicting non-English tweets too could be taken up in future.
  • Add or update comments in the code where necessary.

Expert mode execution steps

This is a very quick recap / summary of the steps required for execution of this code.
Please consider these steps only if you are an expert on Docker, Spark and ecosystem of this project and understand clearly what is being done here.

  • Install and launch Docker.
  • Stop Docker and in the VirtualBox GUI, increase RAM of Docker machine [instance named default and should be in Powered Off state] to at least 2 GB [or more] and # of CPUs to 2 [or more].
  • Start Docker again.
  • Pull the project Docker image and launch it.
    • Might have to wait for ~10 minutes or so [depending on your internet speed].
      docker run -ti -p 4040:4040 -p 8080:8080 -p 8081:8081 -p 9999:9999 -h spark --name=spark p7hb/p7hb-docker-mllib-twitter-sentiment:1.6.2
  • Update application.conf to include your Twitter App OAuth credentials.
  • Execute: /root/exec_spark_jobs.sh
    • Might have to wait for ~10 minutes or so [depending on your internet speed].
  • Point your browser on the host machine to http://192.168.99.100:9999 for visualization.

Note:

Please do not forget to modify the Twitter App OAuth credentials in the file application.conf.
Please check Twitter Developer page for more info.

Helpful links

  1. I am currently hosting this web app on Amazon EC2: http://54.84.252.184:9999/. I will bring it down sometime next week. Update on 19th September, 2016: After running the live app on EC2 for almost a month, I have shutdown this instance today.
  2. Docker Image on Docker Hub Registry: https://hub.docker.com/r/p7hb/p7hb-docker-mllib-twitter-sentiment/.
  3. GitHub URL for source code of the project: https://github.com/P7h/Spark-MLlib-Twitter-Sentiment-Analysis.
  4. GitHub URL for blog post on code walkthru: https://github.com/P7h/Spark-MLlib-Twitter-Sentiment-Analysis/wiki/.
  5. Dockerfile GitHub repo: https://github.com/P7h/p7hb-docker-mllib-twitter-sentiment.

Problems? Questions? Contributions? Contributions welcome

If you find any issues or would like to discuss further, please ping me on my Twitter handle @P7h or drop me an email. Appreciate your help. Thanks!

License License

Copyright © 2016 Prashanth Babu.
Licensed under the Apache License, Version 2.0.

More Repositories

1

IntroToHadoopAndMR__Udacity_Course

🐘 Source code for assignments of Udacity course "Introduction to Hadoop and MapReduce"
Java
117
star
2

docker-spark

🚢 Docker image for Apache Spark
76
star
3

StormTweetsSentimentAnalysis

Computes sentiment analysis of tweets of US States in real-time using Storm.
Java
63
star
4

storm-camel-example

Real-time analysis and visualization with Storm-AMQ-Camel-Websockets-Highcharts integration.
Java
26
star
5

StormTweetsSentimentD3Viz

Computes and visualizes the sentiment analysis of tweets of US States in real-time using Storm.
Java
26
star
6

p7hb-docker-mllib-twitter-sentiment

🚢 Docker image for Twitter Sentiment analysis with Spark MLlib
Shell
7
star
7

Scala-for-the-Impatient__Solutions

My solutions for Scala for the Impatient, 2nd ed.
Jupyter Notebook
4
star
8

StormTweetsSentimentD3UKViz

Computes and visualizes the sentiment analysis of tweets of UK Counties / Regions in real-time using Storm.
Java
4
star
9

Real-Time_Analytics_with_Apache_Storm__Udacity_Course

Source code for lessons and assignments of Udacity-Twitter course "Real-Time Analytics with Apache Storm".
Java
4
star
10

StormTweetsWordCount

Reads Twitter stream and counts words present in Tweets in real-time using Storm.
Java
4
star
11

Coursera__UCSD__Big_Data_Specialization

"Big Data" Specialization -- University of California, San Diego and Coursera
Jupyter Notebook
3
star
12

StormWordCount

Application to demonstrate Storm distributed framework by counting the words [from random sentences] in real-time. This project does not need internet access.
Java
3
star
13

Functional_Programming__HackerRank

Haskell and Scala solutions for Functional Programming challenges on HackerRank.
Scala
2
star
14

edX__Introduction_to_Big_Data_with_Apache_Spark

edX course "Introduction to Big Data with Apache Spark"
2
star
15

docker-haskell

🚢 Docker Image for Stack or GHC and Cabal
2
star
16

ScalaSparkWordCount

Wordcount impl in Scala for Spark
XSLT
1
star
17

IntroToDataScience__Coursera_Course

Assignment source code of Coursera course for Introduction to Data Science
Python
1
star
18

p7hb-docker-spark

🚢 Docker image for Apache Spark
1
star
19

FutureLearn__Learn_to_Code_for_Data_Analysis

My notes of FutureLearn MOOC "Learn to Code for Data Analysis"
Jupyter Notebook
1
star
20

FutureLearn__FP_in_Haskell

My notes of FutureLearn MOOC "Functional Programming in Haskell"
HTML
1
star
21

Data-Visualization-and-Infographics-with-D3

Examples and exercises of online course: "Data Visualization and Infographics with D3".
HTML
1
star
22

Programming_in_Haskell

Code snippets and solutions to exercises of "Programming in Haskell".
Haskell
1
star
23

MOOC_Certifications

Various Certifications and other MOOC Certificates
1
star
24

IntroToPig__5thElephant_Workshop

Code for the workshop on _Introduction to Pig_ at Fifth Elephant, Bangalore, India on 26th July, 2012.
1
star
25

tmux-cheatsheet

tmux shortcuts & cheatsheet
1
star