spark Using MLLib in Scala/Java/Python

Using MLLib in Scala
Following code snippets can be executed in spark-shell.

Binary Classification
The following code snippet illustrates how to load a sample dataset, execute a training algorithm on this training data using a static method in the algorithm object, and make predictions with the resulting model to compute the training error.

 1 import org.apache.spark.SparkContext
 2 import org.apache.spark.mllib.classification.SVMWithSGD
 3 import org.apache.spark.mllib.regression.LabeledPoint
 4 
 5 // Load and parse the data file
 6 val data = sc.textFile("mllib/data/sample_svm_data.txt")
 7 val parsedData = data.map { line =>
 8 val parts = line.split(' ')
 9 LabeledPoint(parts(0).toDouble, parts.tail.map(x => x.toDouble).toArray)
10 }
11 
12 // Run training algorithm to build the model
13 val numIterations = 20
14 val model = SVMWithSGD.train(parsedData, numIterations)
15 
16 // Evaluate model on training examples and compute training error
17 val labelAndPreds = parsedData.map { point =>
18 val prediction = model.predict(point.features)
19 (point.label, prediction)
20 }
21 val trainErr = labelAndPreds.filter(r => r._1 != r._2).count.toDouble / parsedData.count
22 println("Training Error = " + trainErr)

 

The SVMWithSGD.train() method by default performs L2 regularization with the regularization parameter set to 1.0. If we want to configure this algorithm, we can customize SVMWithSGD further by creating a new object directly and calling setter methods. All other MLlib algorithms support customization in this way as well. For example, the following code produces an L1 regularized variant of SVMs with regularization parameter set to 0.1, and runs the training algorithm for 200 iterations.

1 import org.apache.spark.mllib.optimization.L1Updater
2 
3 val svmAlg = new SVMWithSGD()
4 svmAlg.optimizer.setNumIterations(200)
5 .setRegParam(0.1)
6 .setUpdater(new L1Updater)
7 val modelL1 = svmAlg.run(parsedData)

 

Linear Regression
The following example demonstrate how to load training data, parse it as an RDD of LabeledPoint. The example then uses LinearRegressionWithSGD to build a simple linear model to predict label values. We compute the Mean Squared Error at the end to evaluate goodness of fit

 1 import org.apache.spark.mllib.regression.LinearRegressionWithSGD
 2 import org.apache.spark.mllib.regression.LabeledPoint
 3 
 4 // Load and parse the data
 5 val data = sc.textFile("mllib/data/ridge-data/lpsa.data")
 6 val parsedData = data.map { line =>
 7 val parts = line.split(',')
 8 LabeledPoint(parts(0).toDouble, parts(1).split(' ').map(x => x.toDouble).toArray)
 9 }
10 
11 // Building the model
12 val numIterations = 20
13 val model = LinearRegressionWithSGD.train(parsedData, numIterations)
14 
15 // Evaluate model on training examples and compute training error
16 val valuesAndPreds = parsedData.map { point =>
17 val prediction = model.predict(point.features)
18 (point.label, prediction)
19 }
20 val MSE = valuesAndPreds.map{ case(v, p) => math.pow((v - p), 2)}.reduce(_ + _)/valuesAndPreds.count
21 println("training Mean Squared Error = " + MSE)

 

Similarly you can use RidgeRegressionWithSGD and LassoWithSGD and compare training Mean Squared Errors.

Clustering
In the following example after loading and parsing data, we use the KMeans object to cluster the data into two clusters. The number of desired clusters is passed to the algorithm. We then compute Within Set Sum of Squared Error (WSSSE). You can reduce this error measure by increasing k. In fact the optimal k is usually one where there is an “elbow” in the WSSSE graph.

 1 import org.apache.spark.mllib.clustering.KMeans
 2 
 3 // Load and parse the data
 4 val data = sc.textFile("kmeans_data.txt")
 5 val parsedData = data.map( _.split(' ').map(_.toDouble))
 6 
 7 // Cluster the data into two classes using KMeans
 8 val numIterations = 20
 9 val numClusters = 2
10 val clusters = KMeans.train(parsedData, numClusters, numIterations)
11 
12 // Evaluate clustering by computing Within Set Sum of Squared Errors
13 val WSSSE = clusters.computeCost(parsedData)
14 println("Within Set Sum of Squared Errors = " + WSSSE)

 

Collaborative Filtering
In the following example we load rating data. Each row consists of a user, a product and a rating. We use the default ALS.train() method which assumes ratings are explicit. We evaluate the recommendation model by measuring the Mean Squared Error of rating prediction.

 1 import org.apache.spark.mllib.recommendation.ALS
 2 import org.apache.spark.mllib.recommendation.Rating
 3 
 4 // Load and parse the data
 5 val data = sc.textFile("mllib/data/als/test.data")
 6 val ratings = data.map(_.split(',') match {
 7 case Array(user, item, rate) => Rating(user.toInt, item.toInt, rate.toDouble)
 8 })
 9 
10 // Build the recommendation model using ALS
11 val numIterations = 20
12 val model = ALS.train(ratings, 1, 20, 0.01)
13 
14 // Evaluate the model on rating data
15 val usersProducts = ratings.map{ case Rating(user, product, rate) => (user, product)}
16 val predictions = model.predict(usersProducts).map{
17 case Rating(user, product, rate) => ((user, product), rate)
18 }
19 val ratesAndPreds = ratings.map{
20 case Rating(user, product, rate) => ((user, product), rate)
21 }.join(predictions)
22 val MSE = ratesAndPreds.map{
23 case ((user, product), (r1, r2)) => math.pow((r1- r2), 2)
24 }.reduce(_ + _)/ratesAndPreds.count
25 println("Mean Squared Error = " + MSE)

 

If the rating matrix is derived from other source of information (i.e., it is inferred from other signals), you can use the trainImplicit method to get better results.

1 val model = ALS.trainImplicit(ratings, 1, 20, 0.01)

 

Using MLLib in Java
All of MLlib’s methods use Java-friendly types, so you can import and call them there the same way you do in Scala. The only caveat is that the methods take Scala RDD objects, while the Spark Java API uses a separate JavaRDD class. You can convert a Java RDD to a Scala one by calling .rdd() on your JavaRDD object.

Using MLLib in Python
Following examples can be tested in the PySpark shell.

Binary Classification
The following example shows how to load a sample dataset, build Logistic Regression model, and make predictions with the resulting model to compute the training error.

 1 from pyspark.mllib.classification import LogisticRegressionWithSGD
 2 from numpy import array
 3 
 4 # Load and parse the data
 5 data = sc.textFile("mllib/data/sample_svm_data.txt")
 6 parsedData = data.map(lambda line: array([float(x) for x in line.split(' ')]))
 7 model = LogisticRegressionWithSGD.train(parsedData)
 8 
 9 # Build the model
10 labelsAndPreds = parsedData.map(lambda point: (int(point.item(0)),
11 model.predict(point.take(range(1, point.size)))))
12 
13 # Evaluating the model on training data
14 trainErr = labelsAndPreds.filter(lambda (v, p): v != p).count() / float(parsedData.count())
15 print("Training Error = " + str(trainErr))

 

Linear Regression
The following example demonstrate how to load training data, parse it as an RDD of LabeledPoint. The example then uses LinearRegressionWithSGD to build a simple linear model to predict label values. We compute the Mean Squared Error at the end to evaluate goodness of fit

 1 from pyspark.mllib.regression import LinearRegressionWithSGD
 2 from numpy import array
 3 
 4 # Load and parse the data
 5 data = sc.textFile("mllib/data/ridge-data/lpsa.data")
 6 parsedData = data.map(lambda line: array([float(x) for x in line.replace(',', ' ').split(' ')]))
 7 
 8 # Build the model
 9 model = LinearRegressionWithSGD.train(parsedData)
10 
11 # Evaluate the model on training data
12 valuesAndPreds = parsedData.map(lambda point: (point.item(0),
13 model.predict(point.take(range(1, point.size)))))
14 MSE = valuesAndPreds.map(lambda (v, p): (v - p)**2).reduce(lambda x, y: x + y)/valuesAndPreds.count()
15 print("Mean Squared Error = " + str(MSE))

 

Clustering
In the following example after loading and parsing data, we use the KMeans object to cluster the data into two clusters. The number of desired clusters is passed to the algorithm. We then compute Within Set Sum of Squared Error (WSSSE). You can reduce this error measure by increasing k. In fact the optimal k is usually one where there is an “elbow” in the WSSSE graph.

 1 from pyspark.mllib.clustering import KMeans
 2 from numpy import array
 3 from math import sqrt
 4 
 5 # Load and parse the data
 6 data = sc.textFile("kmeans_data.txt")
 7 parsedData = data.map(lambda line: array([float(x) for x in line.split(' ')]))
 8 
 9 # Build the model (cluster the data)
10 clusters = KMeans.train(parsedData, 2, maxIterations=10,
11 runs=30, initialization_mode="random")
12 
13 # Evaluate clustering by computing Within Set Sum of Squared Errors
14 def error(point):
15 center = clusters.centers[clusters.predict(point)]
16 return sqrt(sum([x**2 for x in (point - center)]))
17 
18 WSSSE = parsedData.map(lambda point: error(point)).reduce(lambda x, y: x + y)
19 print("Within Set Sum of Squared Error = " + str(WSSSE))

 

Similarly you can use RidgeRegressionWithSGD and LassoWithSGD and compare training Mean Squared Errors.

Collaborative Filtering
In the following example we load rating data. Each row consists of a user, a product and a rating. We use the default ALS.train() method which assumes ratings are explicit. We evaluate the recommendation by measuring the Mean Squared Error of rating prediction.

 1 from pyspark.mllib.recommendation import ALS
 2 from numpy import array
 3 
 4 # Load and parse the data
 5 data = sc.textFile("mllib/data/als/test.data")
 6 ratings = data.map(lambda line: array([float(x) for x in line.split(',')]))
 7 
 8 # Build the recommendation model using Alternating Least Squares
 9 model = ALS.train(ratings, 1, 20)
10 
11 # Evaluate the model on training data
12 testdata = ratings.map(lambda p: (int(p[0]), int(p[1])))
13 predictions = model.predictAll(testdata).map(lambda r: ((r[0], r[1]), r[2]))
14 ratesAndPreds = ratings.map(lambda r: ((r[0], r[1]), r[2])).join(predictions)
15 MSE = ratesAndPreds.map(lambda r: (r[1][0] - r[1][1])**2).reduce(lambda x, y: x + y)/ratesAndPreds.count()
16 print("Mean Squared Error = " + str(MSE))

 

If the rating matrix is derived from other source of information (i.e., it is inferred from other signals), you can use the trainImplicit method to get better results.

1 # Build the recommendation model using Alternating Least Squares based on implicit ratings
2 model = ALS.trainImplicit(ratings, 1, 20)

 

posted @ 2015-09-06 17:43  苏轶然  阅读(954)  评论(0编辑  收藏  举报