SlideShare a Scribd company logo
© 2016 MapR Technologies 10-1
© 2016 MapR Technologies
Machine Learning with Apache Spark
© 2016 MapR Technologies 10-2
© 2016 MapR Technologies
© 2016 MapR Technologies 10-3
Agenda
• Brief overview of
• Classification
• Clustering
• Collaborative Filtering
• Predicting Flight Delays using a Decision Tree
© 2016 MapR Technologies 10-4
Spark SQL
• Structured Data
• Querying with
SQL/HQL
• DataFrames
Spark Streaming
• Processing of live
streams
• Micro-batching
MLlib
• Machine Learning
• Multiple types of
ML algorithms
GraphX
• Graph processing
• Graph parallel
computations
RDD Transformations and Actions
• Task scheduling
• Memory management
• Fault recovery
• Interacting with storage systems
Spark Core
What is MLlib?
© 2016 MapR Technologies 10-5
MLlib Algorithms and Utilities
Algorithms and Utilities Description
Basic statistics Includes summary statistics, correlations, hypothesis testing, random data
generation
Classification and
regression
Includes methods for linear models, decision trees and Naïve Bayes
Collaborative filtering Supports model-based collaborative filtering using alternating least
squares (ALS) algorithm
Clustering Supports K-means clustering
Dimensionality reduction Supports dimensionality reduction on the RowMatrix class; singular value
decomposition (SVD) and principal component analysis (PCA)
Feature extraction and
transformation
Contains several classes for common feature transformations
© 2016 MapR Technologies 10-6
Examples of ML Algorithms
Supervised
• Classification
– Naïve Bayes
– SVM
– Random Decision
Forests
• Regression
– Linear
– Logistic
Machine Learning
Unsupervised
• Clustering
– K-means
• Dimensionality reduction
– Principal Component
Analysis
– SVD
© 2016 MapR Technologies 10-7
Examples of ML Algorithms
Supervised
• Classification
– Naïve Bayes
– SVM
– Random Decision
Forests
• Regression
– Linear
– Logistic
Machine Learning
Unsupervised
• Clustering
– K-means
• Dimensionality reduction
– Principal Component
Analysis
– SVD
© 2016 MapR Technologies 10-8
Examples of ML Algorithms
Machine Learning
Unsupervised
• Clustering
– K-means
• Dimensionality reduction
– Principal Component
Analysis
– SVD
Supervised
• Classification
– Naïve Bayes
– SVM
– Random Decision
Forests
• Regression
– Linear
– Logistic
© 2016 MapR Technologies 10-9
Three Categories of Techniques for Machine Learning
Collaborative Filtering
(Recommendation)
Classification Clustering
© 2016 MapR Technologies 10-10
Machine Learning: Classification
Classification
Identifies
category for item
© 2016 MapR Technologies 10-11
Classification: Definition
Form of ML that:
• Identifies which category an item belongs to
• Uses supervised learning algorithms
– Data is labeled
Sentiment
© 2016 MapR Technologies 10-12
If it Walks/Swims/Quacks Like a Duck …… Then It Must Be a Duck
swims
walks
quacks
Features:
walks
quacks
swims
Features:
© 2016 MapR Technologies 10-13
Building and Deploying a Classifier Model
Image reference O’Reilly Learning Spark
Spam:
free money now!
get this money
free savings $$$
Training Data
Non-spam:
how are you?
that Spark job
lunch plans
© 2016 MapR Technologies 10-14
Building and Deploying a Classifier Model
Image reference O’Reilly Learning Spark
+
+
̶+
̶ ̶
Feature Vectors
Featurization
Spam:
free money now!
get this money
free savings $$$
Training Data
Non-spam:
how are you?
that Spark job
lunch plans
© 2016 MapR Technologies 10-15
Building and Deploying a Classifier Model
Image reference O’Reilly Learning Spark
+
+
̶+
̶ ̶
Feature Vectors Model
Featurization TrainingSpam:
free money now!
get this money
free savings $$$
Training Data
Non-spam:
how are you?
that Spark job
lunch plans
+
+
̶+
̶ ̶
© 2016 MapR Technologies 10-16
Building and Deploying a Classifier Model
Image reference O’Reilly Learning Spark
+
+
̶+
̶ ̶
Feature Vectors Model
Featurization Training
Model
Evaluation
Best Model
Spam:
free money now!
get this money
free savings $$$
Training Data
Non-spam:
how are you?
that Spark job
lunch plans
+
+
̶+
̶ ̶
+
+
̶+
̶ ̶
+
+
̶+
̶ ̶
+
+
̶+
̶ ̶
© 2016 MapR Technologies 10-17
Machine Learning: Clustering
Classification Clustering
© 2016 MapR Technologies 10-18
Clustering: Definition
• Unsupervised learning task
• Groups objects into clusters of high similarity
© 2016 MapR Technologies 10-19
Clustering: Definition
• Unsupervised learning task
• Groups objects into clusters of high similarity
– Search results grouping
– Grouping of customers
– Anomaly detection
– Text categorization
© 2016 MapR Technologies 10-20
Clustering: Example
• Group similar objects
• Use MLlib K-means algorithm
1. Initialize coordinates to center
of clusters (centroid)
2. Assign all points to nearest
centroid
3. Update centroids to center of
points
4. Repeat until conditions met
© 2016 MapR Technologies 10-21
Three Categories of Techniques for Machine Learning
Collaborative Filtering
(Recommendation)
Classification Clustering
© 2016 MapR Technologies 10-22
Collaborative Filtering with Spark
• Recommend items
– (Filtering)
• Based on user preferences data
– (Collaborative)
4 5 5
5 5
5 ?
Ted
Carol
Bob
A B C
User Item Rating Matrix
© 2016 MapR Technologies 10-23
Train a Model to Make Predictions
Ted and Carol like movies B and C
Bob likes movie B, what might he like?
Bob likes movie B, predict C
Training
Data
ModelAlgorithm
New Data PredictionsModel
4 5 5
5 5
5 ?
Ted
Carol
Bob
A B C
User Item Rating Matrix
© 2016 MapR Technologies 10-24
© 2016 MapR Technologies
Predict Flight Delays
© 2016 MapR Technologies 10-25
Use Case: Flight Data
• Predict if a flight is going to be delayed
• Use Decision Tree for prediction
• Used for Classification and Regression
• Represents tree with nodes, Binary decision at each node
© 2016 MapR Technologies 10-26
Flight Data
© 2016 MapR Technologies 10-27
// Define the schema
case class Flight(dofM: String, dofW: String, carrier: String, tailnum: String,
flnum: Int, org_id: String, origin: String, dest_id: String, dest: String,
crsdeptime: Double, deptime: Double, depdelaymins: Double, crsarrtime: Double,
arrtime: Double, arrdelay: Double, crselapsedtime: Double, dist: Int)
def parseFlight(str: String): Flight = {
val line = str.split(",")
Flight(line(0), line(1), line(2), line(3), line(4).toInt, line(5), line(6),
line(7), line(8), line(9).toDouble, line(10).toDouble, line(11).toDouble,
line(12).toDouble, line(13).toDouble, line(14).toDouble, line(15).toDouble,
line(16).toInt)
}
// load file into a RDD
val rdd = sc.textFile(”flights.csv”)
// create an RDD of Flight objects
val flightRDD = rdd.map(parseFlight).cache()
//Array(Flight(1,3,AA,N338AA,1,12478,JFK,12892,LAX 900.0,914.0,14.0,1225.0,1238.0, 13.0,385.0,2475)
Parse Input
© 2016 MapR Technologies 10-28
Building and Deploying a Classifier Model
+
+
̶+
̶ ̶
Feature Vectors
Featurization
Delayed:
Friday
LAX
AA
Training Data
Not Delayed:
Wednesday
BNA
Delta
© 2016 MapR Technologies 10-29
Classification Learning Problem - Features
Label  delayed and not delayed - delayed if delay > 40 minutes
Features  {day_of_month, weekday, crsdeptime, crsarrtime, carrier,
crselapsedtime, origin, dest}
© 2016 MapR Technologies 10-30
// create map of airline -> number
var carrierMap: Map[String, Int] = Map()
var index: Int = 0
flightsRDD.map(flight => flight.carrier).distinct.collect.foreach(
x => { carrierMap += (x -> index); index += 1 }
)
carrierMap.toString
// String = Map(DL -> 5,US -> 9, AA -> 6, UA -> 4...)
// create map of destination airport -> number
var destMap: Map[String, Int] = Map()
var index2: Int = 0
flightsRDD.map(flight => flight.dest).distinct.collect.foreach(
x => { destMap += (x -> index2); index2 += 1 })
destMap.toString
// Map(JFK -> 214, LAX -> 294, ATL -> 273,MIA -> 175 ...
Transform non-numeric features into numeric values
© 2016 MapR Technologies 10-31
Classification Learning Problem - Features
Label  delayed and not delayed - delayed if delay > 40 minutes
Features  {day_of_month, weekday, crsdeptime, crsarrtime, carrier,
crselapsedtime, origin, dest}
MLLIB Datatypes:
Vector: Contains the feature data points
LabeledPoint: Contains feature vector and label
© 2016 MapR Technologies 10-32
// Defining the features array
val mlprep = flightsRDD.map(flight => {
val monthday = flight.dofM.toInt - 1 // category
val weekday = flight.dofW.toInt - 1 // category
val crsdeptime1 = flight.crsdeptime.toInt
val crsarrtime1 = flight.crsarrtime.toInt
val carrier1 = carrierMap(flight.carrier) // category
val crselapsedtime1 = flight.crselapsedtime.toDouble
val origin1 = originMap(flight.origin) // category
val dest1 = destMap(flight.dest) // category
val delayed = if (flight.depdelaymins.toDouble > 40) 1.0 else 0.0
Array(delayed.toDouble, monthday.toDouble, weekday.toDouble, crsdeptime1.toDouble, crsarrtime1.toDouble,
carrier1.toDouble, crselapsedtime1.toDouble, origin1.toDouble, dest1.toDouble)
})
mlprep.take(1)
//Array(Array(0.0, 0.0, 2.0, 900.0, 1225.0, 6.0, 385.0, 214.0, 294.0))
val mldata = mlprep.map(x => LabeledPoint(x(0),Vectors.dense(x(1),x(2),x(3),x(4), x(5),x(6),
x(7), x(8))))
mldata.take(1)
// Array[LabeledPoint] = Array((0.0,[0.0,2.0,900.0,1225.0,6.0,385.0,214.0,294.0]))
Define the features, Create LabeledPoint with Vector
© 2016 MapR Technologies 10-33
ML Cross-Validation Process
Data
Model
Training/
Building
Training
Set
Test Model
Predictions
Test
Set
Train/Test loop
© 2016 MapR Technologies 10-34
ML Cross-Validation Process
Data
Model
Training/
Building
Training
Set
Test Model
Predictions
Test
Set
Train/Test loop
Train algorithm with training dataset
Use test dataset on trained algorithm
© 2016 MapR Technologies 10-35
ML Cross-Validation Process
Data
Model
Training/
Building
Training
Set
Test Model
Predictions
Test
Set
Train/Test loop
Train algorithm with training dataset
Use test dataset on trained algorithm
© 2016 MapR Technologies 10-36
Build Model
Split data into:
• Training data RDD (80%)
• Test data RDD (20%)
Data
Build
Model
Training
Set
Test
Set
© 2016 MapR Technologies 10-37
// Randomly split RDD into training data RDD (80%) and test
data RDD (20%)
val splits = mldata.randomSplit(Array(0.8, 0.2))
val trainingRDD = splits(0).cache()
val testRDD = splits(1).cache()
testData.take(1)
//Array[LabeledPoint] =
Array((0.0,[18.0,6.0,900.0,1225.0,6.0,385.0,214.0,294.0]))
Split Data
© 2016 MapR Technologies 10-38
Build Model
Training Set with Labels, Build a model
Data
Build
Model
Training
Set
Test
Set
© 2016 MapR Technologies 10-39
Use Case: Flight Data
• Predict if a flight is going to be delayed
• Use Decision Tree for prediction
• Used for Classification and Regression
• Represents tree with nodes
• Binary decision at each node
© 2016 MapR Technologies 10-40
// set ranges for categorical features
var categoricalFeaturesInfo = Map[Int, Int]()
categoricalFeaturesInfo += (0 -> 31) //dofM 31 categories
categoricalFeaturesInfo += (1 -> 7) //dofW 7 categories
categoricalFeaturesInfo += (4 -> carrierMap.size) //number of carriers
categoricalFeaturesInfo += (6 -> originMap.size) //number of origin airports
categoricalFeaturesInfo += (7 -> destMap.size) //number of dest airports
val numClasses = 2
val impurity = "gini"
val maxDepth = 9
val maxBins = 7000
// call DecisionTree trainClassifier with the trainingData , which returns the model
val model = DecisionTree.trainClassifier(trainingData, numClasses, categoricalFeaturesInfo,
impurity, maxDepth, maxBins)
Build Model
© 2016 MapR Technologies 10-41
// print out the decision tree
model.toDebugString
// 0=dofM 4=carrier 3=crsarrtime1 6=origin
res20: String =
DecisionTreeModel classifier of depth 9 with 919 nodes
If (feature 0 in {11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0,19.0,20.0,21.0,
22.0,23.0,24.0,25.0,26.0,27.0,30.0})
If (feature 4 in {0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,13.0})
If (feature 3 <= 1603.0)
If (feature 0 in {11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0,19.0})
If (feature 6 in {0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,10.0,11.0,12.0,13.0...
Build Model
© 2016 MapR Technologies 10-42
Get Predictions
Test
Data
Without label
Predict
Delay or Not
Model
© 2016 MapR Technologies 10-43
// Get Predictions,create RDD of test Label, test Prediction
val labelAndPreds = testData.map { point =>
val prediction = model.predict(point.features)
(point.label, prediction)
}
labelAndPreds.take(1)
// Label, Prediction
//Array((0.0,0.0))
Get Predictions
© 2016 MapR Technologies 10-44
To Learn More:
• Download example code
– https://github.com/caroljmcdonald/sparkmldecisiontree
• Read explanation of example code
– https://www.mapr.com/blog/apache-spark-machine-learning-tutorial
• Engage with us!
– https://www.mapr.com/blog/author/carol-mcdonald
– https://community.mapr.com
© 2016 MapR Technologies 10-45
// get instances where label != prediction
val wrongPrediction =(labelAndPreds.filter{
case (label, prediction) => ( label !=prediction)
})
val wrong= wrongPrediction.count()
res35: Long = 11040
val ratioWrong=wrong.toDouble/testData.count()
ratioWrong: Double = 0.3157443157443157
Test Model

More Related Content

What's hot (20)

PDF
Introduction to Spark
Carol McDonald
 
PPTX
Apache Spark Machine Learning Decision Trees
Carol McDonald
 
PDF
Fast Cars, Big Data How Streaming can help Formula 1
Carol McDonald
 
PDF
MapR & Skytree:
MapR Technologies
 
PDF
Anomaly Detection in Telecom with Spark - Tugdual Grall - Codemotion Amsterda...
Codemotion
 
PPTX
MapR 5.2 Product Update
MapR Technologies
 
PDF
Advanced Threat Detection on Streaming Data
Carol McDonald
 
PDF
Applying Machine Learning to Live Patient Data
Carol McDonald
 
PPTX
Cognitive computing with big data, high tech and low tech approaches
Ted Dunning
 
PDF
How Big Data is Reducing Costs and Improving Outcomes in Health Care
Carol McDonald
 
PDF
Streaming Patterns Revolutionary Architectures with the Kafka API
Carol McDonald
 
PDF
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Carol McDonald
 
PDF
Getting Started with HBase
Carol McDonald
 
PDF
Streaming patterns revolutionary architectures
Carol McDonald
 
PPTX
Real time-hadoop
Ted Dunning
 
PDF
Predicting Flight Delays with Spark Machine Learning
Carol McDonald
 
PDF
On-Prem Solution for the Selection of Wind Energy Models
Databricks
 
PPTX
What's new in Apache Mahout
Ted Dunning
 
PDF
Apache Spark streaming and HBase
Carol McDonald
 
PDF
NoSQL HBase schema design and SQL with Apache Drill
Carol McDonald
 
Introduction to Spark
Carol McDonald
 
Apache Spark Machine Learning Decision Trees
Carol McDonald
 
Fast Cars, Big Data How Streaming can help Formula 1
Carol McDonald
 
MapR & Skytree:
MapR Technologies
 
Anomaly Detection in Telecom with Spark - Tugdual Grall - Codemotion Amsterda...
Codemotion
 
MapR 5.2 Product Update
MapR Technologies
 
Advanced Threat Detection on Streaming Data
Carol McDonald
 
Applying Machine Learning to Live Patient Data
Carol McDonald
 
Cognitive computing with big data, high tech and low tech approaches
Ted Dunning
 
How Big Data is Reducing Costs and Improving Outcomes in Health Care
Carol McDonald
 
Streaming Patterns Revolutionary Architectures with the Kafka API
Carol McDonald
 
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Carol McDonald
 
Getting Started with HBase
Carol McDonald
 
Streaming patterns revolutionary architectures
Carol McDonald
 
Real time-hadoop
Ted Dunning
 
Predicting Flight Delays with Spark Machine Learning
Carol McDonald
 
On-Prem Solution for the Selection of Wind Energy Models
Databricks
 
What's new in Apache Mahout
Ted Dunning
 
Apache Spark streaming and HBase
Carol McDonald
 
NoSQL HBase schema design and SQL with Apache Drill
Carol McDonald
 

Similar to Free Code Friday - Machine Learning with Apache Spark (20)

PDF
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Carol McDonald
 
PDF
Apache Spark Machine Learning
Carol McDonald
 
PDF
Live Tutorial – Streaming Real-Time Events Using Apache APIs
MapR Technologies
 
PDF
Demystifying AI, Machine Learning and Deep Learning
Carol McDonald
 
PDF
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Carol McDonald
 
PDF
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Carol McDonald
 
PPTX
Introduction overviewmachinelearning sig Door Lucas Jellema
Getting value from IoT, Integration and Data Analytics
 
PDF
Introduction to Machine Learning with SciKit-Learn
Benjamin Bengfort
 
PPTX
The Art of Intelligence – A Practical Introduction Machine Learning for Oracl...
Lucas Jellema
 
PDF
Predictive Maintenance Using Recurrent Neural Networks
Justin Brandenburg
 
PPTX
B4UConference_machine learning_deeplearning
Hoa Le
 
PPTX
Introduction to Machine Learning - An overview and first step for candidate d...
Lucas Jellema
 
PDF
Machine learning with Apache Spark MLlib | Big Data Hadoop Spark Tutorial | C...
CloudxLab
 
PDF
Recent Developments in Spark MLlib and Beyond
DataWorks Summit
 
PDF
Azure Machine Learning
Mostafa
 
PDF
Recent Developments in Spark MLlib and Beyond
Xiangrui Meng
 
PPTX
BIG DATA AND MACHINE LEARNING
Umair Shafique
 
PDF
Map r chicago_advanalytics_oct_meetup
Alan Iovine
 
PDF
Big Data LDN 2018: DATA OPERATIONS PROBLEMS CREATED BY DEEP LEARNING, AND HOW...
Matt Stubbs
 
PDF
Building predictive models in Azure Machine Learning
Mostafa
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Carol McDonald
 
Apache Spark Machine Learning
Carol McDonald
 
Live Tutorial – Streaming Real-Time Events Using Apache APIs
MapR Technologies
 
Demystifying AI, Machine Learning and Deep Learning
Carol McDonald
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Carol McDonald
 
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Carol McDonald
 
Introduction overviewmachinelearning sig Door Lucas Jellema
Getting value from IoT, Integration and Data Analytics
 
Introduction to Machine Learning with SciKit-Learn
Benjamin Bengfort
 
The Art of Intelligence – A Practical Introduction Machine Learning for Oracl...
Lucas Jellema
 
Predictive Maintenance Using Recurrent Neural Networks
Justin Brandenburg
 
B4UConference_machine learning_deeplearning
Hoa Le
 
Introduction to Machine Learning - An overview and first step for candidate d...
Lucas Jellema
 
Machine learning with Apache Spark MLlib | Big Data Hadoop Spark Tutorial | C...
CloudxLab
 
Recent Developments in Spark MLlib and Beyond
DataWorks Summit
 
Azure Machine Learning
Mostafa
 
Recent Developments in Spark MLlib and Beyond
Xiangrui Meng
 
BIG DATA AND MACHINE LEARNING
Umair Shafique
 
Map r chicago_advanalytics_oct_meetup
Alan Iovine
 
Big Data LDN 2018: DATA OPERATIONS PROBLEMS CREATED BY DEEP LEARNING, AND HOW...
Matt Stubbs
 
Building predictive models in Azure Machine Learning
Mostafa
 
Ad

More from MapR Technologies (20)

PPTX
Converging your data landscape
MapR Technologies
 
PPTX
ML Workshop 2: Machine Learning Model Comparison & Evaluation
MapR Technologies
 
PPTX
Self-Service Data Science for Leveraging ML & AI on All of Your Data
MapR Technologies
 
PPTX
Enabling Real-Time Business with Change Data Capture
MapR Technologies
 
PPTX
Machine Learning for Chickens, Autonomous Driving and a 3-year-old Who Won’t ...
MapR Technologies
 
PPTX
ML Workshop 1: A New Architecture for Machine Learning Logistics
MapR Technologies
 
PPTX
Machine Learning Success: The Key to Easier Model Management
MapR Technologies
 
PPTX
Data Warehouse Modernization: Accelerating Time-To-Action
MapR Technologies
 
PPTX
Bringing Structure, Scalability, and Services to Cloud-Scale Storage
MapR Technologies
 
PDF
Live Machine Learning Tutorial: Churn Prediction
MapR Technologies
 
PDF
An Introduction to the MapR Converged Data Platform
MapR Technologies
 
PPTX
How to Leverage the Cloud for Business Solutions | Strata Data Conference Lon...
MapR Technologies
 
PPTX
Best Practices for Data Convergence in Healthcare
MapR Technologies
 
PPTX
Geo-Distributed Big Data and Analytics
MapR Technologies
 
PPTX
MapR Product Update - Spring 2017
MapR Technologies
 
PPTX
3 Benefits of Multi-Temperature Data Management for Data Analytics
MapR Technologies
 
PPTX
Cisco & MapR bring 3 Superpowers to SAP HANA Deployments
MapR Technologies
 
PPTX
MapR and Cisco Make IT Better
MapR Technologies
 
PPTX
Evolving from RDBMS to NoSQL + SQL
MapR Technologies
 
PPTX
Evolving Beyond the Data Lake: A Story of Wind and Rain
MapR Technologies
 
Converging your data landscape
MapR Technologies
 
ML Workshop 2: Machine Learning Model Comparison & Evaluation
MapR Technologies
 
Self-Service Data Science for Leveraging ML & AI on All of Your Data
MapR Technologies
 
Enabling Real-Time Business with Change Data Capture
MapR Technologies
 
Machine Learning for Chickens, Autonomous Driving and a 3-year-old Who Won’t ...
MapR Technologies
 
ML Workshop 1: A New Architecture for Machine Learning Logistics
MapR Technologies
 
Machine Learning Success: The Key to Easier Model Management
MapR Technologies
 
Data Warehouse Modernization: Accelerating Time-To-Action
MapR Technologies
 
Bringing Structure, Scalability, and Services to Cloud-Scale Storage
MapR Technologies
 
Live Machine Learning Tutorial: Churn Prediction
MapR Technologies
 
An Introduction to the MapR Converged Data Platform
MapR Technologies
 
How to Leverage the Cloud for Business Solutions | Strata Data Conference Lon...
MapR Technologies
 
Best Practices for Data Convergence in Healthcare
MapR Technologies
 
Geo-Distributed Big Data and Analytics
MapR Technologies
 
MapR Product Update - Spring 2017
MapR Technologies
 
3 Benefits of Multi-Temperature Data Management for Data Analytics
MapR Technologies
 
Cisco & MapR bring 3 Superpowers to SAP HANA Deployments
MapR Technologies
 
MapR and Cisco Make IT Better
MapR Technologies
 
Evolving from RDBMS to NoSQL + SQL
MapR Technologies
 
Evolving Beyond the Data Lake: A Story of Wind and Rain
MapR Technologies
 
Ad

Recently uploaded (20)

PDF
apidays Helsinki & North 2025 - Monetizing AI APIs: The New API Economy, Alla...
apidays
 
PDF
OPPOTUS - Malaysias on Malaysia 1Q2025.pdf
Oppotus
 
PDF
apidays Helsinki & North 2025 - API-Powered Journeys: Mobility in an API-Driv...
apidays
 
PDF
apidays Singapore 2025 - From API Intelligence to API Governance by Harsha Ch...
apidays
 
PPTX
Listify-Intelligent-Voice-to-Catalog-Agent.pptx
nareshkottees
 
PPTX
apidays Singapore 2025 - Generative AI Landscape Building a Modern Data Strat...
apidays
 
PDF
The European Business Wallet: Why It Matters and How It Powers the EUDI Ecosy...
Lal Chandran
 
PDF
Avatar for apidays apidays PRO June 07, 2025 0 5 apidays Helsinki & North 2...
apidays
 
PPTX
SlideEgg_501298-Agentic AI.pptx agentic ai
530BYManoj
 
PDF
Development and validation of the Japanese version of the Organizational Matt...
Yoga Tokuyoshi
 
PPTX
apidays Helsinki & North 2025 - Vero APIs - Experiences of API development in...
apidays
 
PPT
Growth of Public Expendituuure_55423.ppt
NavyaDeora
 
PDF
apidays Singapore 2025 - The API Playbook for AI by Shin Wee Chuang (PAND AI)
apidays
 
PPTX
apidays Helsinki & North 2025 - Running a Successful API Program: Best Practi...
apidays
 
PPTX
apidays Singapore 2025 - Designing for Change, Julie Schiller (Google)
apidays
 
PPTX
apidays Helsinki & North 2025 - APIs at Scale: Designing for Alignment, Trust...
apidays
 
PPTX
apidays Munich 2025 - Building an AWS Serverless Application with Terraform, ...
apidays
 
PDF
Using AI/ML for Space Biology Research
VICTOR MAESTRE RAMIREZ
 
PPTX
b6057ea5-8e8c-4415-90c0-ed8e9666ffcd.pptx
Anees487379
 
PPTX
apidays Helsinki & North 2025 - Agentic AI: A Friend or Foe?, Merja Kajava (A...
apidays
 
apidays Helsinki & North 2025 - Monetizing AI APIs: The New API Economy, Alla...
apidays
 
OPPOTUS - Malaysias on Malaysia 1Q2025.pdf
Oppotus
 
apidays Helsinki & North 2025 - API-Powered Journeys: Mobility in an API-Driv...
apidays
 
apidays Singapore 2025 - From API Intelligence to API Governance by Harsha Ch...
apidays
 
Listify-Intelligent-Voice-to-Catalog-Agent.pptx
nareshkottees
 
apidays Singapore 2025 - Generative AI Landscape Building a Modern Data Strat...
apidays
 
The European Business Wallet: Why It Matters and How It Powers the EUDI Ecosy...
Lal Chandran
 
Avatar for apidays apidays PRO June 07, 2025 0 5 apidays Helsinki & North 2...
apidays
 
SlideEgg_501298-Agentic AI.pptx agentic ai
530BYManoj
 
Development and validation of the Japanese version of the Organizational Matt...
Yoga Tokuyoshi
 
apidays Helsinki & North 2025 - Vero APIs - Experiences of API development in...
apidays
 
Growth of Public Expendituuure_55423.ppt
NavyaDeora
 
apidays Singapore 2025 - The API Playbook for AI by Shin Wee Chuang (PAND AI)
apidays
 
apidays Helsinki & North 2025 - Running a Successful API Program: Best Practi...
apidays
 
apidays Singapore 2025 - Designing for Change, Julie Schiller (Google)
apidays
 
apidays Helsinki & North 2025 - APIs at Scale: Designing for Alignment, Trust...
apidays
 
apidays Munich 2025 - Building an AWS Serverless Application with Terraform, ...
apidays
 
Using AI/ML for Space Biology Research
VICTOR MAESTRE RAMIREZ
 
b6057ea5-8e8c-4415-90c0-ed8e9666ffcd.pptx
Anees487379
 
apidays Helsinki & North 2025 - Agentic AI: A Friend or Foe?, Merja Kajava (A...
apidays
 

Free Code Friday - Machine Learning with Apache Spark

  • 1. © 2016 MapR Technologies 10-1 © 2016 MapR Technologies Machine Learning with Apache Spark
  • 2. © 2016 MapR Technologies 10-2 © 2016 MapR Technologies
  • 3. © 2016 MapR Technologies 10-3 Agenda • Brief overview of • Classification • Clustering • Collaborative Filtering • Predicting Flight Delays using a Decision Tree
  • 4. © 2016 MapR Technologies 10-4 Spark SQL • Structured Data • Querying with SQL/HQL • DataFrames Spark Streaming • Processing of live streams • Micro-batching MLlib • Machine Learning • Multiple types of ML algorithms GraphX • Graph processing • Graph parallel computations RDD Transformations and Actions • Task scheduling • Memory management • Fault recovery • Interacting with storage systems Spark Core What is MLlib?
  • 5. © 2016 MapR Technologies 10-5 MLlib Algorithms and Utilities Algorithms and Utilities Description Basic statistics Includes summary statistics, correlations, hypothesis testing, random data generation Classification and regression Includes methods for linear models, decision trees and Naïve Bayes Collaborative filtering Supports model-based collaborative filtering using alternating least squares (ALS) algorithm Clustering Supports K-means clustering Dimensionality reduction Supports dimensionality reduction on the RowMatrix class; singular value decomposition (SVD) and principal component analysis (PCA) Feature extraction and transformation Contains several classes for common feature transformations
  • 6. © 2016 MapR Technologies 10-6 Examples of ML Algorithms Supervised • Classification – Naïve Bayes – SVM – Random Decision Forests • Regression – Linear – Logistic Machine Learning Unsupervised • Clustering – K-means • Dimensionality reduction – Principal Component Analysis – SVD
  • 7. © 2016 MapR Technologies 10-7 Examples of ML Algorithms Supervised • Classification – Naïve Bayes – SVM – Random Decision Forests • Regression – Linear – Logistic Machine Learning Unsupervised • Clustering – K-means • Dimensionality reduction – Principal Component Analysis – SVD
  • 8. © 2016 MapR Technologies 10-8 Examples of ML Algorithms Machine Learning Unsupervised • Clustering – K-means • Dimensionality reduction – Principal Component Analysis – SVD Supervised • Classification – Naïve Bayes – SVM – Random Decision Forests • Regression – Linear – Logistic
  • 9. © 2016 MapR Technologies 10-9 Three Categories of Techniques for Machine Learning Collaborative Filtering (Recommendation) Classification Clustering
  • 10. © 2016 MapR Technologies 10-10 Machine Learning: Classification Classification Identifies category for item
  • 11. © 2016 MapR Technologies 10-11 Classification: Definition Form of ML that: • Identifies which category an item belongs to • Uses supervised learning algorithms – Data is labeled Sentiment
  • 12. © 2016 MapR Technologies 10-12 If it Walks/Swims/Quacks Like a Duck …… Then It Must Be a Duck swims walks quacks Features: walks quacks swims Features:
  • 13. © 2016 MapR Technologies 10-13 Building and Deploying a Classifier Model Image reference O’Reilly Learning Spark Spam: free money now! get this money free savings $$$ Training Data Non-spam: how are you? that Spark job lunch plans
  • 14. © 2016 MapR Technologies 10-14 Building and Deploying a Classifier Model Image reference O’Reilly Learning Spark + + ̶+ ̶ ̶ Feature Vectors Featurization Spam: free money now! get this money free savings $$$ Training Data Non-spam: how are you? that Spark job lunch plans
  • 15. © 2016 MapR Technologies 10-15 Building and Deploying a Classifier Model Image reference O’Reilly Learning Spark + + ̶+ ̶ ̶ Feature Vectors Model Featurization TrainingSpam: free money now! get this money free savings $$$ Training Data Non-spam: how are you? that Spark job lunch plans + + ̶+ ̶ ̶
  • 16. © 2016 MapR Technologies 10-16 Building and Deploying a Classifier Model Image reference O’Reilly Learning Spark + + ̶+ ̶ ̶ Feature Vectors Model Featurization Training Model Evaluation Best Model Spam: free money now! get this money free savings $$$ Training Data Non-spam: how are you? that Spark job lunch plans + + ̶+ ̶ ̶ + + ̶+ ̶ ̶ + + ̶+ ̶ ̶ + + ̶+ ̶ ̶
  • 17. © 2016 MapR Technologies 10-17 Machine Learning: Clustering Classification Clustering
  • 18. © 2016 MapR Technologies 10-18 Clustering: Definition • Unsupervised learning task • Groups objects into clusters of high similarity
  • 19. © 2016 MapR Technologies 10-19 Clustering: Definition • Unsupervised learning task • Groups objects into clusters of high similarity – Search results grouping – Grouping of customers – Anomaly detection – Text categorization
  • 20. © 2016 MapR Technologies 10-20 Clustering: Example • Group similar objects • Use MLlib K-means algorithm 1. Initialize coordinates to center of clusters (centroid) 2. Assign all points to nearest centroid 3. Update centroids to center of points 4. Repeat until conditions met
  • 21. © 2016 MapR Technologies 10-21 Three Categories of Techniques for Machine Learning Collaborative Filtering (Recommendation) Classification Clustering
  • 22. © 2016 MapR Technologies 10-22 Collaborative Filtering with Spark • Recommend items – (Filtering) • Based on user preferences data – (Collaborative) 4 5 5 5 5 5 ? Ted Carol Bob A B C User Item Rating Matrix
  • 23. © 2016 MapR Technologies 10-23 Train a Model to Make Predictions Ted and Carol like movies B and C Bob likes movie B, what might he like? Bob likes movie B, predict C Training Data ModelAlgorithm New Data PredictionsModel 4 5 5 5 5 5 ? Ted Carol Bob A B C User Item Rating Matrix
  • 24. © 2016 MapR Technologies 10-24 © 2016 MapR Technologies Predict Flight Delays
  • 25. © 2016 MapR Technologies 10-25 Use Case: Flight Data • Predict if a flight is going to be delayed • Use Decision Tree for prediction • Used for Classification and Regression • Represents tree with nodes, Binary decision at each node
  • 26. © 2016 MapR Technologies 10-26 Flight Data
  • 27. © 2016 MapR Technologies 10-27 // Define the schema case class Flight(dofM: String, dofW: String, carrier: String, tailnum: String, flnum: Int, org_id: String, origin: String, dest_id: String, dest: String, crsdeptime: Double, deptime: Double, depdelaymins: Double, crsarrtime: Double, arrtime: Double, arrdelay: Double, crselapsedtime: Double, dist: Int) def parseFlight(str: String): Flight = { val line = str.split(",") Flight(line(0), line(1), line(2), line(3), line(4).toInt, line(5), line(6), line(7), line(8), line(9).toDouble, line(10).toDouble, line(11).toDouble, line(12).toDouble, line(13).toDouble, line(14).toDouble, line(15).toDouble, line(16).toInt) } // load file into a RDD val rdd = sc.textFile(”flights.csv”) // create an RDD of Flight objects val flightRDD = rdd.map(parseFlight).cache() //Array(Flight(1,3,AA,N338AA,1,12478,JFK,12892,LAX 900.0,914.0,14.0,1225.0,1238.0, 13.0,385.0,2475) Parse Input
  • 28. © 2016 MapR Technologies 10-28 Building and Deploying a Classifier Model + + ̶+ ̶ ̶ Feature Vectors Featurization Delayed: Friday LAX AA Training Data Not Delayed: Wednesday BNA Delta
  • 29. © 2016 MapR Technologies 10-29 Classification Learning Problem - Features Label  delayed and not delayed - delayed if delay > 40 minutes Features  {day_of_month, weekday, crsdeptime, crsarrtime, carrier, crselapsedtime, origin, dest}
  • 30. © 2016 MapR Technologies 10-30 // create map of airline -> number var carrierMap: Map[String, Int] = Map() var index: Int = 0 flightsRDD.map(flight => flight.carrier).distinct.collect.foreach( x => { carrierMap += (x -> index); index += 1 } ) carrierMap.toString // String = Map(DL -> 5,US -> 9, AA -> 6, UA -> 4...) // create map of destination airport -> number var destMap: Map[String, Int] = Map() var index2: Int = 0 flightsRDD.map(flight => flight.dest).distinct.collect.foreach( x => { destMap += (x -> index2); index2 += 1 }) destMap.toString // Map(JFK -> 214, LAX -> 294, ATL -> 273,MIA -> 175 ... Transform non-numeric features into numeric values
  • 31. © 2016 MapR Technologies 10-31 Classification Learning Problem - Features Label  delayed and not delayed - delayed if delay > 40 minutes Features  {day_of_month, weekday, crsdeptime, crsarrtime, carrier, crselapsedtime, origin, dest} MLLIB Datatypes: Vector: Contains the feature data points LabeledPoint: Contains feature vector and label
  • 32. © 2016 MapR Technologies 10-32 // Defining the features array val mlprep = flightsRDD.map(flight => { val monthday = flight.dofM.toInt - 1 // category val weekday = flight.dofW.toInt - 1 // category val crsdeptime1 = flight.crsdeptime.toInt val crsarrtime1 = flight.crsarrtime.toInt val carrier1 = carrierMap(flight.carrier) // category val crselapsedtime1 = flight.crselapsedtime.toDouble val origin1 = originMap(flight.origin) // category val dest1 = destMap(flight.dest) // category val delayed = if (flight.depdelaymins.toDouble > 40) 1.0 else 0.0 Array(delayed.toDouble, monthday.toDouble, weekday.toDouble, crsdeptime1.toDouble, crsarrtime1.toDouble, carrier1.toDouble, crselapsedtime1.toDouble, origin1.toDouble, dest1.toDouble) }) mlprep.take(1) //Array(Array(0.0, 0.0, 2.0, 900.0, 1225.0, 6.0, 385.0, 214.0, 294.0)) val mldata = mlprep.map(x => LabeledPoint(x(0),Vectors.dense(x(1),x(2),x(3),x(4), x(5),x(6), x(7), x(8)))) mldata.take(1) // Array[LabeledPoint] = Array((0.0,[0.0,2.0,900.0,1225.0,6.0,385.0,214.0,294.0])) Define the features, Create LabeledPoint with Vector
  • 33. © 2016 MapR Technologies 10-33 ML Cross-Validation Process Data Model Training/ Building Training Set Test Model Predictions Test Set Train/Test loop
  • 34. © 2016 MapR Technologies 10-34 ML Cross-Validation Process Data Model Training/ Building Training Set Test Model Predictions Test Set Train/Test loop Train algorithm with training dataset Use test dataset on trained algorithm
  • 35. © 2016 MapR Technologies 10-35 ML Cross-Validation Process Data Model Training/ Building Training Set Test Model Predictions Test Set Train/Test loop Train algorithm with training dataset Use test dataset on trained algorithm
  • 36. © 2016 MapR Technologies 10-36 Build Model Split data into: • Training data RDD (80%) • Test data RDD (20%) Data Build Model Training Set Test Set
  • 37. © 2016 MapR Technologies 10-37 // Randomly split RDD into training data RDD (80%) and test data RDD (20%) val splits = mldata.randomSplit(Array(0.8, 0.2)) val trainingRDD = splits(0).cache() val testRDD = splits(1).cache() testData.take(1) //Array[LabeledPoint] = Array((0.0,[18.0,6.0,900.0,1225.0,6.0,385.0,214.0,294.0])) Split Data
  • 38. © 2016 MapR Technologies 10-38 Build Model Training Set with Labels, Build a model Data Build Model Training Set Test Set
  • 39. © 2016 MapR Technologies 10-39 Use Case: Flight Data • Predict if a flight is going to be delayed • Use Decision Tree for prediction • Used for Classification and Regression • Represents tree with nodes • Binary decision at each node
  • 40. © 2016 MapR Technologies 10-40 // set ranges for categorical features var categoricalFeaturesInfo = Map[Int, Int]() categoricalFeaturesInfo += (0 -> 31) //dofM 31 categories categoricalFeaturesInfo += (1 -> 7) //dofW 7 categories categoricalFeaturesInfo += (4 -> carrierMap.size) //number of carriers categoricalFeaturesInfo += (6 -> originMap.size) //number of origin airports categoricalFeaturesInfo += (7 -> destMap.size) //number of dest airports val numClasses = 2 val impurity = "gini" val maxDepth = 9 val maxBins = 7000 // call DecisionTree trainClassifier with the trainingData , which returns the model val model = DecisionTree.trainClassifier(trainingData, numClasses, categoricalFeaturesInfo, impurity, maxDepth, maxBins) Build Model
  • 41. © 2016 MapR Technologies 10-41 // print out the decision tree model.toDebugString // 0=dofM 4=carrier 3=crsarrtime1 6=origin res20: String = DecisionTreeModel classifier of depth 9 with 919 nodes If (feature 0 in {11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0,19.0,20.0,21.0, 22.0,23.0,24.0,25.0,26.0,27.0,30.0}) If (feature 4 in {0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,13.0}) If (feature 3 <= 1603.0) If (feature 0 in {11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0,19.0}) If (feature 6 in {0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,10.0,11.0,12.0,13.0... Build Model
  • 42. © 2016 MapR Technologies 10-42 Get Predictions Test Data Without label Predict Delay or Not Model
  • 43. © 2016 MapR Technologies 10-43 // Get Predictions,create RDD of test Label, test Prediction val labelAndPreds = testData.map { point => val prediction = model.predict(point.features) (point.label, prediction) } labelAndPreds.take(1) // Label, Prediction //Array((0.0,0.0)) Get Predictions
  • 44. © 2016 MapR Technologies 10-44 To Learn More: • Download example code – https://github.com/caroljmcdonald/sparkmldecisiontree • Read explanation of example code – https://www.mapr.com/blog/apache-spark-machine-learning-tutorial • Engage with us! – https://www.mapr.com/blog/author/carol-mcdonald – https://community.mapr.com
  • 45. © 2016 MapR Technologies 10-45 // get instances where label != prediction val wrongPrediction =(labelAndPreds.filter{ case (label, prediction) => ( label !=prediction) }) val wrong= wrongPrediction.count() res35: Long = 11040 val ratioWrong=wrong.toDouble/testData.count() ratioWrong: Double = 0.3157443157443157 Test Model