Apache Spark Machine Learning Example with Scala

In this Apache Spark Machine Learning example, Spark MLlib will be introduced and Scala source code reviewed.  This post and accompanying screencast videos will demonstrate a custom Spark MLlib Spark driver application.  Then, the Spark MLLib Scala source code will be examined.  There will be many topics shown and explained, but first, let’s describe a few machine learning concepts.

Machine Learning Key Concepts

What is machine learning?

Machine learning is creating and using models that are learned from data.  You might also hear machine learning referred to as predictive modeling or data mining.  

What are three examples of machine learning?

  • spam prediction
  • fraudulent credit card transaction prediction
  • a product or advertisement recommendation engine

There are two types of machine learning models: supervised and unsupervised.  Supervised models contain a set of data labelled with correct answers while unsupervised does not contain labelling.

Examples of Supervised machine learning models

  • k-nearest neighbors – example: predict how a person might vote if you know how their neighbors are voting
  • naive bayes – example: determine if an incoming email is spam
  • linear regression – try to determine if two variables are correlated
  • decision trees – uses a structure to represent a number of possible decision paths and an outcome for each path

Examples of Unsupervised machine learning models

  • clustering – works with unlabelled data and attempts to “cluster” it.  For example, data set showing where millionaires live probably has clusters in places like Beverly Hills and Manhattan
  • Latent Dirichlet Analysis (LDA) – natural language processing commonly used to identify common topics in text or a set of documents
  • neural networks – examples: handwriting recognition and face image detection

When building models used to make predictions, we often train a model based on an existing data set.  The model may be re-trained many times as more and more training data set becomes available.  For example, we would re-train a recommendation engine based on collaborative filtering as we learned more about events that led to product sales or targeted engagement metrics.

Apache Spark Machine Learning Example (with Scala)

Let’s show the demo of an Apache Spark machine learning program.  In the following demo, we begin by training the k-means clustering model and then use this trained model to predict the language of an incoming text stream from Slack.

This example is built upon a previous Apache Spark Streaming tutorial which streams data from a Slack team site.  These videos and more are also available in our Spark training courses.  See Resources section below for links.

But, let’s move forward with the demo:

 

 

Apache Spark Machine Learning Scala Source Code Review

Ok, now that we have the demo in mind, let’s review the Spark MLLib relevant code.  Again, the links to source code may be found in Resources section below.  Let’s start with the entry into our Spark Machine Learning example and what was called during spark-submit deploys in the demo, SlackMLApp:

The code above is what contains the main method and what is called from spark-submit.  As you can hopefully see, we will either train a new model or use an existing model when running the SlackStreamingTask.  It depends on the incoming command line arguments such as trainData, modelLocation and slackToken.

In this Spark machine learning example source code analysis and review, we will next focus on 1) the code used to train the model in KMeanTrainTask and 2) using the model to make predictions in SlackStreamingTask.

First, let’s open the relevant portion KMeanTrainTask

When calling train we will attempt to remove any previously saved model in removePrevious. ( removePrevious isn’t shown because it’s not relevant for our focus on machine learning with Apache Spark.)  So, let’s set up a new RDD called trainRdd.  Since textFile accepts a String argument of a directory, it will read all files contained in the directory which we called with “input”.

Next, we must convert the elements (rows of text) in the RDD to a format suitable for KMeans.  We do this by calling Utils.featurize which looks like this:

Now, if we go back to our KMeansTrain task object, we’re in a position to train our model using KMeans.train function with parsedData and numClusters and numIterations.  Afterwards, we save the model and send a few example predictions of clustering to the console by iterating over example and sending to println.

Now that we have a model trained, let’s see SlackStreamingTask

The Spark MLlib code which is making clustering predictions with a previously saved model is clusters.predict.  Before it is called, we map over the DStream and use featurize again in order to use with predict.  We are returning a DStream with the original text received from Slack and the predicted cluster.

If the Spark driver program had been called with predictOutput value, the output would be saved as text files.

Here’s another screencast which I’m describing the code in more detail.

Resources

Source code: https://github.com/tmcgrath/spark-course/tree/master/spark-ml

Background on Machine Learning: http://www.slideshare.net/ToddMcGrath1/machine-learning-with-apache-spark-62310284

Spark MLlib: http://www.slideshare.net/ToddMcGrath1/machine-learning-with-spark-mllib

Spark Machine Learning chapter from Learning Spark Summary 

Spark with Scala training course

 

 

Featured image credit: https://flic.kr/p/ainDUT

3 thoughts on “Apache Spark Machine Learning Example with Scala”

  1. NIkitha

    Hi todd, Thanks so much for such a great tutorial. I followed your previous one too and then this machine learning. I compiled sbt and the jar file has been created successfully. When I ran from single stand-alone mode, I got a message saying “16/10/12 12:48:17 WARN TaskSchedulerImpl: Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources” and this message keep on repeating again and again. So I tried to run the same from server which has 7 slaves. But then again I am getting the same message. Kindly tell me how to resolve this issue. Thanks so much in advance.

    • Todd M Post Author

      Nikitha,
      Did you get this resolved? Can you post a screenshot of Spark UI to verify workers are running and available?

      Todd

  2. Nikitha

    Hi thanks for the tutorial. when i tried to run the jar file for training, I ma keep getting the message again and again and again:
    16/10/13 03:37:23 WARN scheduler.TaskSchedulerImpl: Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources
    Can u plz help me ? thanks alot

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">