Skip to content

Commit 266a814

Browse files
jkbradleymengxr
authored andcommitted
[SPARK-4575] [mllib] [docs] spark.ml pipelines doc + bug fixes
Documentation: * Added ml-guide.md, linked from mllib-guide.md * Updated mllib-guide.md with small section pointing to ml-guide.md Examples: * CrossValidatorExample * SimpleParamsExample * (I copied these + the SimpleTextClassificationPipeline example into the ml-guide.md) Bug fixes: * PipelineModel: did not use ParamMaps correctly * UnaryTransformer: issues with TypeTag serialization (Thanks to mengxr for that fix!) CC: mengxr shivaram etrain Documentation for Pipelines: I know the docs are not complete, but the goal is to have enough to let interested people get started using spark.ml and to add more docs once the package is more established/complete. Author: Joseph K. Bradley <[email protected]> Author: jkbradley <[email protected]> Author: Xiangrui Meng <[email protected]> Closes #3588 from jkbradley/ml-package-docs and squashes the following commits: d393b5c [Joseph K. Bradley] fixed bug in Pipeline (typo from last commit). updated examples for CV and Params for spark.ml c38469c [Joseph K. Bradley] Updated ml-guide with CV examples 99f88c2 [Joseph K. Bradley] Fixed bug in PipelineModel.transform* with usage of params. Updated CrossValidatorExample to use more training examples so it is less likely to get a 0-size fold. ea34dc6 [jkbradley] Merge pull request #4 from mengxr/ml-package-docs 3b83ec0 [Xiangrui Meng] replace TypeTag with explicit datatype 41ad9b1 [Joseph K. Bradley] Added examples for spark.ml: SimpleParamsExample + Java version, CrossValidatorExample + Java version. CrossValidatorExample not working yet. Added programming guide for spark.ml, but need to add CrossValidatorExample to it once CrossValidatorExample works. (cherry picked from commit 469a6e5) Signed-off-by: Xiangrui Meng <[email protected]>
1 parent bf720ef commit 266a814

File tree

17 files changed

+1205
-24
lines changed

17 files changed

+1205
-24
lines changed

docs/img/ml-Pipeline.png

72.3 KB
Loading

docs/img/ml-PipelineModel.png

74.2 KB
Loading

docs/img/ml-Pipelines.pptx

55.4 KB
Binary file not shown.

docs/ml-guide.md

Lines changed: 702 additions & 0 deletions
Large diffs are not rendered by default.

docs/mllib-guide.md

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
layout: global
3-
title: Machine Learning Library (MLlib)
3+
title: Machine Learning Library (MLlib) Programming Guide
44
---
55

66
MLlib is Spark's scalable machine learning library consisting of common learning algorithms and utilities,
@@ -35,6 +35,17 @@ MLlib is under active development.
3535
The APIs marked `Experimental`/`DeveloperApi` may change in future releases,
3636
and the migration guide below will explain all changes between releases.
3737

38+
# spark.ml: The New ML Package
39+
40+
Spark 1.2 includes a new machine learning package called `spark.ml`, currently an alpha component but potentially a successor to `spark.mllib`. The `spark.ml` package aims to replace the old APIs with a cleaner, more uniform set of APIs which will help users create full machine learning pipelines.
41+
42+
See the **[spark.ml programming guide](ml-guide.html)** for more information on this package.
43+
44+
Users can use algorithms from either of the two packages, but APIs may differ. Currently, `spark.ml` offers a subset of the algorithms from `spark.mllib`.
45+
46+
Developers should contribute new algorithms to `spark.mllib` and can optionally contribute to `spark.ml`.
47+
See the `spark.ml` programming guide linked above for more details.
48+
3849
# Dependencies
3950

4051
MLlib uses the linear algebra package [Breeze](http://www.scalanlp.org/),
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
package org.apache.spark.examples.ml;
19+
20+
import java.util.List;
21+
22+
import com.google.common.collect.Lists;
23+
24+
import org.apache.spark.SparkConf;
25+
import org.apache.spark.api.java.JavaSparkContext;
26+
import org.apache.spark.ml.Model;
27+
import org.apache.spark.ml.Pipeline;
28+
import org.apache.spark.ml.PipelineStage;
29+
import org.apache.spark.ml.classification.LogisticRegression;
30+
import org.apache.spark.ml.evaluation.BinaryClassificationEvaluator;
31+
import org.apache.spark.ml.feature.HashingTF;
32+
import org.apache.spark.ml.feature.Tokenizer;
33+
import org.apache.spark.ml.param.ParamMap;
34+
import org.apache.spark.ml.tuning.CrossValidator;
35+
import org.apache.spark.ml.tuning.CrossValidatorModel;
36+
import org.apache.spark.ml.tuning.ParamGridBuilder;
37+
import org.apache.spark.sql.api.java.JavaSQLContext;
38+
import org.apache.spark.sql.api.java.JavaSchemaRDD;
39+
import org.apache.spark.sql.api.java.Row;
40+
41+
/**
42+
* A simple example demonstrating model selection using CrossValidator.
43+
* This example also demonstrates how Pipelines are Estimators.
44+
*
45+
* This example uses the Java bean classes {@link org.apache.spark.examples.ml.LabeledDocument} and
46+
* {@link org.apache.spark.examples.ml.Document} defined in the Scala example
47+
* {@link org.apache.spark.examples.ml.SimpleTextClassificationPipeline}.
48+
*
49+
* Run with
50+
* <pre>
51+
* bin/run-example ml.JavaCrossValidatorExample
52+
* </pre>
53+
*/
54+
public class JavaCrossValidatorExample {
55+
56+
public static void main(String[] args) {
57+
SparkConf conf = new SparkConf().setAppName("JavaCrossValidatorExample");
58+
JavaSparkContext jsc = new JavaSparkContext(conf);
59+
JavaSQLContext jsql = new JavaSQLContext(jsc);
60+
61+
// Prepare training documents, which are labeled.
62+
List<LabeledDocument> localTraining = Lists.newArrayList(
63+
new LabeledDocument(0L, "a b c d e spark", 1.0),
64+
new LabeledDocument(1L, "b d", 0.0),
65+
new LabeledDocument(2L, "spark f g h", 1.0),
66+
new LabeledDocument(3L, "hadoop mapreduce", 0.0),
67+
new LabeledDocument(4L, "b spark who", 1.0),
68+
new LabeledDocument(5L, "g d a y", 0.0),
69+
new LabeledDocument(6L, "spark fly", 1.0),
70+
new LabeledDocument(7L, "was mapreduce", 0.0),
71+
new LabeledDocument(8L, "e spark program", 1.0),
72+
new LabeledDocument(9L, "a e c l", 0.0),
73+
new LabeledDocument(10L, "spark compile", 1.0),
74+
new LabeledDocument(11L, "hadoop software", 0.0));
75+
JavaSchemaRDD training =
76+
jsql.applySchema(jsc.parallelize(localTraining), LabeledDocument.class);
77+
78+
// Configure an ML pipeline, which consists of three stages: tokenizer, hashingTF, and lr.
79+
Tokenizer tokenizer = new Tokenizer()
80+
.setInputCol("text")
81+
.setOutputCol("words");
82+
HashingTF hashingTF = new HashingTF()
83+
.setNumFeatures(1000)
84+
.setInputCol(tokenizer.getOutputCol())
85+
.setOutputCol("features");
86+
LogisticRegression lr = new LogisticRegression()
87+
.setMaxIter(10)
88+
.setRegParam(0.01);
89+
Pipeline pipeline = new Pipeline()
90+
.setStages(new PipelineStage[] {tokenizer, hashingTF, lr});
91+
92+
// We now treat the Pipeline as an Estimator, wrapping it in a CrossValidator instance.
93+
// This will allow us to jointly choose parameters for all Pipeline stages.
94+
// A CrossValidator requires an Estimator, a set of Estimator ParamMaps, and an Evaluator.
95+
CrossValidator crossval = new CrossValidator()
96+
.setEstimator(pipeline)
97+
.setEvaluator(new BinaryClassificationEvaluator());
98+
// We use a ParamGridBuilder to construct a grid of parameters to search over.
99+
// With 3 values for hashingTF.numFeatures and 2 values for lr.regParam,
100+
// this grid will have 3 x 2 = 6 parameter settings for CrossValidator to choose from.
101+
ParamMap[] paramGrid = new ParamGridBuilder()
102+
.addGrid(hashingTF.numFeatures(), new int[]{10, 100, 1000})
103+
.addGrid(lr.regParam(), new double[]{0.1, 0.01})
104+
.build();
105+
crossval.setEstimatorParamMaps(paramGrid);
106+
crossval.setNumFolds(2); // Use 3+ in practice
107+
108+
// Run cross-validation, and choose the best set of parameters.
109+
CrossValidatorModel cvModel = crossval.fit(training);
110+
111+
// Prepare test documents, which are unlabeled.
112+
List<Document> localTest = Lists.newArrayList(
113+
new Document(4L, "spark i j k"),
114+
new Document(5L, "l m n"),
115+
new Document(6L, "mapreduce spark"),
116+
new Document(7L, "apache hadoop"));
117+
JavaSchemaRDD test = jsql.applySchema(jsc.parallelize(localTest), Document.class);
118+
119+
// Make predictions on test documents. cvModel uses the best model found (lrModel).
120+
cvModel.transform(test).registerAsTable("prediction");
121+
JavaSchemaRDD predictions = jsql.sql("SELECT id, text, score, prediction FROM prediction");
122+
for (Row r: predictions.collect()) {
123+
System.out.println("(" + r.get(0) + ", " + r.get(1) + ") --> score=" + r.get(2)
124+
+ ", prediction=" + r.get(3));
125+
}
126+
}
127+
}
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
package org.apache.spark.examples.ml;
19+
20+
import java.util.List;
21+
22+
import com.google.common.collect.Lists;
23+
24+
import org.apache.spark.SparkConf;
25+
import org.apache.spark.api.java.JavaSparkContext;
26+
import org.apache.spark.ml.classification.LogisticRegressionModel;
27+
import org.apache.spark.ml.param.ParamMap;
28+
import org.apache.spark.ml.classification.LogisticRegression;
29+
import org.apache.spark.mllib.linalg.Vectors;
30+
import org.apache.spark.mllib.regression.LabeledPoint;
31+
import org.apache.spark.sql.api.java.JavaSQLContext;
32+
import org.apache.spark.sql.api.java.JavaSchemaRDD;
33+
import org.apache.spark.sql.api.java.Row;
34+
35+
/**
36+
* A simple example demonstrating ways to specify parameters for Estimators and Transformers.
37+
* Run with
38+
* {{{
39+
* bin/run-example ml.JavaSimpleParamsExample
40+
* }}}
41+
*/
42+
public class JavaSimpleParamsExample {
43+
44+
public static void main(String[] args) {
45+
SparkConf conf = new SparkConf().setAppName("JavaSimpleParamsExample");
46+
JavaSparkContext jsc = new JavaSparkContext(conf);
47+
JavaSQLContext jsql = new JavaSQLContext(jsc);
48+
49+
// Prepare training data.
50+
// We use LabeledPoint, which is a case class. Spark SQL can convert RDDs of Java Beans
51+
// into SchemaRDDs, where it uses the bean metadata to infer the schema.
52+
List<LabeledPoint> localTraining = Lists.newArrayList(
53+
new LabeledPoint(1.0, Vectors.dense(0.0, 1.1, 0.1)),
54+
new LabeledPoint(0.0, Vectors.dense(2.0, 1.0, -1.0)),
55+
new LabeledPoint(0.0, Vectors.dense(2.0, 1.3, 1.0)),
56+
new LabeledPoint(1.0, Vectors.dense(0.0, 1.2, -0.5)));
57+
JavaSchemaRDD training = jsql.applySchema(jsc.parallelize(localTraining), LabeledPoint.class);
58+
59+
// Create a LogisticRegression instance. This instance is an Estimator.
60+
LogisticRegression lr = new LogisticRegression();
61+
// Print out the parameters, documentation, and any default values.
62+
System.out.println("LogisticRegression parameters:\n" + lr.explainParams() + "\n");
63+
64+
// We may set parameters using setter methods.
65+
lr.setMaxIter(10)
66+
.setRegParam(0.01);
67+
68+
// Learn a LogisticRegression model. This uses the parameters stored in lr.
69+
LogisticRegressionModel model1 = lr.fit(training);
70+
// Since model1 is a Model (i.e., a Transformer produced by an Estimator),
71+
// we can view the parameters it used during fit().
72+
// This prints the parameter (name: value) pairs, where names are unique IDs for this
73+
// LogisticRegression instance.
74+
System.out.println("Model 1 was fit using parameters: " + model1.fittingParamMap());
75+
76+
// We may alternatively specify parameters using a ParamMap.
77+
ParamMap paramMap = new ParamMap();
78+
paramMap.put(lr.maxIter().w(20)); // Specify 1 Param.
79+
paramMap.put(lr.maxIter(), 30); // This overwrites the original maxIter.
80+
paramMap.put(lr.regParam().w(0.1), lr.threshold().w(0.55)); // Specify multiple Params.
81+
82+
// One can also combine ParamMaps.
83+
ParamMap paramMap2 = new ParamMap();
84+
paramMap2.put(lr.scoreCol().w("probability")); // Change output column name
85+
ParamMap paramMapCombined = paramMap.$plus$plus(paramMap2);
86+
87+
// Now learn a new model using the paramMapCombined parameters.
88+
// paramMapCombined overrides all parameters set earlier via lr.set* methods.
89+
LogisticRegressionModel model2 = lr.fit(training, paramMapCombined);
90+
System.out.println("Model 2 was fit using parameters: " + model2.fittingParamMap());
91+
92+
// Prepare test documents.
93+
List<LabeledPoint> localTest = Lists.newArrayList(
94+
new LabeledPoint(1.0, Vectors.dense(-1.0, 1.5, 1.3)),
95+
new LabeledPoint(0.0, Vectors.dense(3.0, 2.0, -0.1)),
96+
new LabeledPoint(1.0, Vectors.dense(0.0, 2.2, -1.5)));
97+
JavaSchemaRDD test = jsql.applySchema(jsc.parallelize(localTest), LabeledPoint.class);
98+
99+
// Make predictions on test documents using the Transformer.transform() method.
100+
// LogisticRegression.transform will only use the 'features' column.
101+
// Note that model2.transform() outputs a 'probability' column instead of the usual 'score'
102+
// column since we renamed the lr.scoreCol parameter previously.
103+
model2.transform(test).registerAsTable("results");
104+
JavaSchemaRDD results =
105+
jsql.sql("SELECT features, label, probability, prediction FROM results");
106+
for (Row r: results.collect()) {
107+
System.out.println("(" + r.get(0) + ", " + r.get(1) + ") -> prob=" + r.get(2)
108+
+ ", prediction=" + r.get(3));
109+
}
110+
}
111+
}

examples/src/main/java/org/apache/spark/examples/ml/JavaSimpleTextClassificationPipeline.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -80,14 +80,14 @@ public static void main(String[] args) {
8080
new Document(5L, "l m n"),
8181
new Document(6L, "mapreduce spark"),
8282
new Document(7L, "apache hadoop"));
83-
JavaSchemaRDD test =
84-
jsql.applySchema(jsc.parallelize(localTest), Document.class);
83+
JavaSchemaRDD test = jsql.applySchema(jsc.parallelize(localTest), Document.class);
8584

8685
// Make predictions on test documents.
8786
model.transform(test).registerAsTable("prediction");
8887
JavaSchemaRDD predictions = jsql.sql("SELECT id, text, score, prediction FROM prediction");
8988
for (Row r: predictions.collect()) {
90-
System.out.println(r);
89+
System.out.println("(" + r.get(0) + ", " + r.get(1) + ") --> score=" + r.get(2)
90+
+ ", prediction=" + r.get(3));
9191
}
9292
}
9393
}
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
package org.apache.spark.examples.ml
19+
20+
import org.apache.spark.{SparkConf, SparkContext}
21+
import org.apache.spark.SparkContext._
22+
import org.apache.spark.ml.Pipeline
23+
import org.apache.spark.ml.classification.LogisticRegression
24+
import org.apache.spark.ml.evaluation.BinaryClassificationEvaluator
25+
import org.apache.spark.ml.feature.{HashingTF, Tokenizer}
26+
import org.apache.spark.ml.tuning.{ParamGridBuilder, CrossValidator}
27+
import org.apache.spark.sql.{Row, SQLContext}
28+
29+
/**
30+
* A simple example demonstrating model selection using CrossValidator.
31+
* This example also demonstrates how Pipelines are Estimators.
32+
*
33+
* This example uses the [[LabeledDocument]] and [[Document]] case classes from
34+
* [[SimpleTextClassificationPipeline]].
35+
*
36+
* Run with
37+
* {{{
38+
* bin/run-example ml.CrossValidatorExample
39+
* }}}
40+
*/
41+
object CrossValidatorExample {
42+
43+
def main(args: Array[String]) {
44+
val conf = new SparkConf().setAppName("CrossValidatorExample")
45+
val sc = new SparkContext(conf)
46+
val sqlContext = new SQLContext(sc)
47+
import sqlContext._
48+
49+
// Prepare training documents, which are labeled.
50+
val training = sparkContext.parallelize(Seq(
51+
LabeledDocument(0L, "a b c d e spark", 1.0),
52+
LabeledDocument(1L, "b d", 0.0),
53+
LabeledDocument(2L, "spark f g h", 1.0),
54+
LabeledDocument(3L, "hadoop mapreduce", 0.0),
55+
LabeledDocument(4L, "b spark who", 1.0),
56+
LabeledDocument(5L, "g d a y", 0.0),
57+
LabeledDocument(6L, "spark fly", 1.0),
58+
LabeledDocument(7L, "was mapreduce", 0.0),
59+
LabeledDocument(8L, "e spark program", 1.0),
60+
LabeledDocument(9L, "a e c l", 0.0),
61+
LabeledDocument(10L, "spark compile", 1.0),
62+
LabeledDocument(11L, "hadoop software", 0.0)))
63+
64+
// Configure an ML pipeline, which consists of three stages: tokenizer, hashingTF, and lr.
65+
val tokenizer = new Tokenizer()
66+
.setInputCol("text")
67+
.setOutputCol("words")
68+
val hashingTF = new HashingTF()
69+
.setInputCol(tokenizer.getOutputCol)
70+
.setOutputCol("features")
71+
val lr = new LogisticRegression()
72+
.setMaxIter(10)
73+
val pipeline = new Pipeline()
74+
.setStages(Array(tokenizer, hashingTF, lr))
75+
76+
// We now treat the Pipeline as an Estimator, wrapping it in a CrossValidator instance.
77+
// This will allow us to jointly choose parameters for all Pipeline stages.
78+
// A CrossValidator requires an Estimator, a set of Estimator ParamMaps, and an Evaluator.
79+
val crossval = new CrossValidator()
80+
.setEstimator(pipeline)
81+
.setEvaluator(new BinaryClassificationEvaluator)
82+
// We use a ParamGridBuilder to construct a grid of parameters to search over.
83+
// With 3 values for hashingTF.numFeatures and 2 values for lr.regParam,
84+
// this grid will have 3 x 2 = 6 parameter settings for CrossValidator to choose from.
85+
val paramGrid = new ParamGridBuilder()
86+
.addGrid(hashingTF.numFeatures, Array(10, 100, 1000))
87+
.addGrid(lr.regParam, Array(0.1, 0.01))
88+
.build()
89+
crossval.setEstimatorParamMaps(paramGrid)
90+
crossval.setNumFolds(2) // Use 3+ in practice
91+
92+
// Run cross-validation, and choose the best set of parameters.
93+
val cvModel = crossval.fit(training)
94+
95+
// Prepare test documents, which are unlabeled.
96+
val test = sparkContext.parallelize(Seq(
97+
Document(4L, "spark i j k"),
98+
Document(5L, "l m n"),
99+
Document(6L, "mapreduce spark"),
100+
Document(7L, "apache hadoop")))
101+
102+
// Make predictions on test documents. cvModel uses the best model found (lrModel).
103+
cvModel.transform(test)
104+
.select('id, 'text, 'score, 'prediction)
105+
.collect()
106+
.foreach { case Row(id: Long, text: String, score: Double, prediction: Double) =>
107+
println("(" + id + ", " + text + ") --> score=" + score + ", prediction=" + prediction)
108+
}
109+
}
110+
}

0 commit comments

Comments
 (0)