-
Notifications
You must be signed in to change notification settings - Fork 28.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[SPARK-4586][MLLIB] Python API for ML pipeline and parameters #4151
Closed
Closed
Changes from 33 commits
Commits
Show all changes
34 commits
Select commit
Hold shift + click to select a range
33b68e0
a working LR
mengxr 46eea43
a pipeline in python
mengxr a3015cf
add Estimator and Transformer
mengxr dadd84e
add base classes and docs
mengxr c18dca1
make the example working
mengxr d9ea77c
update doc
mengxr 17ecfb9
code gen for shared params
mengxr bce72f4
Merge remote-tracking branch 'apache/master' into SPARK-4586
mengxr d0c5bb8
a working copy
mengxr 56de571
fix style
mengxr d3e8dbe
more docs
mengxr 05e3e40
update example
mengxr f4d0fe6
use LabeledDocument and Document in example
mengxr d5efd34
update doc conf and move embedded param map to instance attribute
mengxr f66ba0c
make params a property
mengxr 1dcc17e
update code gen and make param appear in the doc
mengxr 46fa147
update mllib/pom.xml to include python files in the assembly
mengxr 036ca04
gen numFeatures
mengxr 5153cff
simplify java models
mengxr 0586c7b
add more comments to the example
mengxr ba0ba1e
add unit tests for pipeline
mengxr 7521d1c
add unit tests to HashingTF and Tokenizer
mengxr a4f4dbf
add unit test for LR
mengxr 0882513
update doc style
mengxr 090b3a3
Merge branch 'master' of github.com:apache/spark into ml
1dca16a
refactor
fc59a02
Merge remote-tracking branch 'apache/master' into SPARK-4586
mengxr 78638df
Merge branch 'SPARK-4586' of github.com:mengxr/spark into ml
54ca7df
fix tests
14ae7e2
fix docs
dd1256b
Merge remote-tracking branch 'apache/master' into SPARK-4586
mengxr 44c2405
Merge pull request #2 from davies/ml
mengxr edbd6fe
move Identifiable to ml.util
mengxr 415268e
remove inherit_doc from __init__
mengxr File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
79 changes: 79 additions & 0 deletions
79
examples/src/main/python/ml/simple_text_classification_pipeline.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
# | ||
# Licensed to the Apache Software Foundation (ASF) under one or more | ||
# contributor license agreements. See the NOTICE file distributed with | ||
# this work for additional information regarding copyright ownership. | ||
# The ASF licenses this file to You under the Apache License, Version 2.0 | ||
# (the "License"); you may not use this file except in compliance with | ||
# the License. You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
# | ||
|
||
from pyspark import SparkContext | ||
from pyspark.sql import SQLContext, Row | ||
from pyspark.ml import Pipeline | ||
from pyspark.ml.feature import HashingTF, Tokenizer | ||
from pyspark.ml.classification import LogisticRegression | ||
|
||
|
||
""" | ||
A simple text classification pipeline that recognizes "spark" from | ||
input text. This is to show how to create and configure a Spark ML | ||
pipeline in Python. Run with: | ||
|
||
bin/spark-submit examples/src/main/python/ml/simple_text_classification_pipeline.py | ||
""" | ||
|
||
|
||
if __name__ == "__main__": | ||
sc = SparkContext(appName="SimpleTextClassificationPipeline") | ||
sqlCtx = SQLContext(sc) | ||
|
||
# Prepare training documents, which are labeled. | ||
LabeledDocument = Row('id', 'text', 'label') | ||
training = sqlCtx.inferSchema( | ||
sc.parallelize([(0L, "a b c d e spark", 1.0), | ||
(1L, "b d", 0.0), | ||
(2L, "spark f g h", 1.0), | ||
(3L, "hadoop mapreduce", 0.0)]) | ||
.map(lambda x: LabeledDocument(*x))) | ||
|
||
# Configure an ML pipeline, which consists of tree stages: tokenizer, hashingTF, and lr. | ||
tokenizer = Tokenizer() \ | ||
.setInputCol("text") \ | ||
.setOutputCol("words") | ||
hashingTF = HashingTF() \ | ||
.setInputCol(tokenizer.getOutputCol()) \ | ||
.setOutputCol("features") | ||
lr = LogisticRegression() \ | ||
.setMaxIter(10) \ | ||
.setRegParam(0.01) | ||
pipeline = Pipeline() \ | ||
.setStages([tokenizer, hashingTF, lr]) | ||
|
||
# Fit the pipeline to training documents. | ||
model = pipeline.fit(training) | ||
|
||
# Prepare test documents, which are unlabeled. | ||
Document = Row('id', 'text') | ||
test = sqlCtx.inferSchema( | ||
sc.parallelize([(4L, "spark i j k"), | ||
(5L, "l m n"), | ||
(6L, "mapreduce spark"), | ||
(7L, "apache hadoop")]) | ||
.map(lambda x: Document(*x))) | ||
|
||
# Make predictions on test documents and print columns of interest. | ||
prediction = model.transform(test) | ||
prediction.registerTempTable("prediction") | ||
selected = sqlCtx.sql("SELECT id, text, prediction from prediction") | ||
for row in selected.collect(): | ||
print row | ||
|
||
sc.stop() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -14,6 +14,7 @@ Contents: | |
pyspark | ||
pyspark.sql | ||
pyspark.streaming | ||
pyspark.ml | ||
pyspark.mllib | ||
|
||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
pyspark.ml package | ||
===================== | ||
|
||
Submodules | ||
---------- | ||
|
||
pyspark.ml module | ||
----------------- | ||
|
||
.. automodule:: pyspark.ml | ||
:members: | ||
:undoc-members: | ||
:inherited-members: | ||
|
||
pyspark.ml.feature module | ||
------------------------- | ||
|
||
.. automodule:: pyspark.ml.feature | ||
:members: | ||
:undoc-members: | ||
:inherited-members: | ||
|
||
pyspark.ml.classification module | ||
-------------------------------- | ||
|
||
.. automodule:: pyspark.ml.classification | ||
:members: | ||
:undoc-members: | ||
:inherited-members: |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -9,6 +9,7 @@ Subpackages | |
|
||
pyspark.sql | ||
pyspark.streaming | ||
pyspark.ml | ||
pyspark.mllib | ||
|
||
Contents | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
# | ||
# Licensed to the Apache Software Foundation (ASF) under one or more | ||
# contributor license agreements. See the NOTICE file distributed with | ||
# this work for additional information regarding copyright ownership. | ||
# The ASF licenses this file to You under the Apache License, Version 2.0 | ||
# (the "License"); you may not use this file except in compliance with | ||
# the License. You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
# | ||
|
||
from pyspark.ml.param import * | ||
from pyspark.ml.pipeline import * | ||
|
||
__all__ = ["Param", "Params", "Transformer", "Estimator", "Pipeline"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
# | ||
# Licensed to the Apache Software Foundation (ASF) under one or more | ||
# contributor license agreements. See the NOTICE file distributed with | ||
# this work for additional information regarding copyright ownership. | ||
# The ASF licenses this file to You under the Apache License, Version 2.0 | ||
# (the "License"); you may not use this file except in compliance with | ||
# the License. You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
# | ||
|
||
from pyspark.ml.util import inherit_doc | ||
from pyspark.ml.wrapper import JavaEstimator, JavaModel | ||
from pyspark.ml.param.shared import HasFeaturesCol, HasLabelCol, HasPredictionCol, HasMaxIter,\ | ||
HasRegParam | ||
|
||
|
||
__all__ = ['LogisticRegression', 'LogisticRegressionModel'] | ||
|
||
|
||
@inherit_doc | ||
class LogisticRegression(JavaEstimator, HasFeaturesCol, HasLabelCol, HasPredictionCol, HasMaxIter, | ||
HasRegParam): | ||
""" | ||
Logistic regression. | ||
|
||
>>> from pyspark.sql import Row | ||
>>> from pyspark.mllib.linalg import Vectors | ||
>>> dataset = sqlCtx.inferSchema(sc.parallelize([ \ | ||
Row(label=1.0, features=Vectors.dense(1.0)), \ | ||
Row(label=0.0, features=Vectors.sparse(1, [], []))])) | ||
>>> lr = LogisticRegression() \ | ||
.setMaxIter(5) \ | ||
.setRegParam(0.01) | ||
>>> model = lr.fit(dataset) | ||
>>> test0 = sqlCtx.inferSchema(sc.parallelize([Row(features=Vectors.dense(-1.0))])) | ||
>>> print model.transform(test0).head().prediction | ||
0.0 | ||
>>> test1 = sqlCtx.inferSchema(sc.parallelize([Row(features=Vectors.sparse(1, [0], [1.0]))])) | ||
>>> print model.transform(test1).head().prediction | ||
1.0 | ||
""" | ||
_java_class = "org.apache.spark.ml.classification.LogisticRegression" | ||
|
||
def _create_model(self, java_model): | ||
return LogisticRegressionModel(java_model) | ||
|
||
|
||
class LogisticRegressionModel(JavaModel): | ||
""" | ||
Model fitted by LogisticRegression. | ||
""" | ||
|
||
|
||
if __name__ == "__main__": | ||
import doctest | ||
from pyspark.context import SparkContext | ||
from pyspark.sql import SQLContext | ||
globs = globals().copy() | ||
# The small batch size here ensures that we see multiple batches, | ||
# even in these small test examples: | ||
sc = SparkContext("local[2]", "ml.feature tests") | ||
sqlCtx = SQLContext(sc) | ||
globs['sc'] = sc | ||
globs['sqlCtx'] = sqlCtx | ||
(failure_count, test_count) = doctest.testmod( | ||
globs=globs, optionflags=doctest.ELLIPSIS) | ||
sc.stop() | ||
if failure_count: | ||
exit(-1) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
# | ||
# Licensed to the Apache Software Foundation (ASF) under one or more | ||
# contributor license agreements. See the NOTICE file distributed with | ||
# this work for additional information regarding copyright ownership. | ||
# The ASF licenses this file to You under the Apache License, Version 2.0 | ||
# (the "License"); you may not use this file except in compliance with | ||
# the License. You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
# | ||
|
||
from pyspark.ml.param.shared import HasInputCol, HasOutputCol, HasNumFeatures | ||
from pyspark.ml.util import inherit_doc | ||
from pyspark.ml.wrapper import JavaTransformer | ||
|
||
__all__ = ['Tokenizer', 'HashingTF'] | ||
|
||
|
||
@inherit_doc | ||
class Tokenizer(JavaTransformer, HasInputCol, HasOutputCol): | ||
""" | ||
A tokenizer that converts the input string to lowercase and then | ||
splits it by white spaces. | ||
|
||
>>> from pyspark.sql import Row | ||
>>> dataset = sqlCtx.inferSchema(sc.parallelize([Row(text="a b c")])) | ||
>>> tokenizer = Tokenizer() \ | ||
.setInputCol("text") \ | ||
.setOutputCol("words") | ||
>>> print tokenizer.transform(dataset).head() | ||
Row(text=u'a b c', words=[u'a', u'b', u'c']) | ||
>>> print tokenizer.transform(dataset, {tokenizer.outputCol: "tokens"}).head() | ||
Row(text=u'a b c', tokens=[u'a', u'b', u'c']) | ||
""" | ||
|
||
_java_class = "org.apache.spark.ml.feature.Tokenizer" | ||
|
||
|
||
@inherit_doc | ||
class HashingTF(JavaTransformer, HasInputCol, HasOutputCol, HasNumFeatures): | ||
""" | ||
Maps a sequence of terms to their term frequencies using the | ||
hashing trick. | ||
|
||
>>> from pyspark.sql import Row | ||
>>> dataset = sqlCtx.inferSchema(sc.parallelize([Row(words=["a", "b", "c"])])) | ||
>>> hashingTF = HashingTF() \ | ||
.setNumFeatures(10) \ | ||
.setInputCol("words") \ | ||
.setOutputCol("features") | ||
>>> print hashingTF.transform(dataset).head().features | ||
(10,[7,8,9],[1.0,1.0,1.0]) | ||
>>> params = {hashingTF.numFeatures: 5, hashingTF.outputCol: "vector"} | ||
>>> print hashingTF.transform(dataset, params).head().vector | ||
(5,[2,3,4],[1.0,1.0,1.0]) | ||
""" | ||
|
||
_java_class = "org.apache.spark.ml.feature.HashingTF" | ||
|
||
|
||
if __name__ == "__main__": | ||
import doctest | ||
from pyspark.context import SparkContext | ||
from pyspark.sql import SQLContext | ||
globs = globals().copy() | ||
# The small batch size here ensures that we see multiple batches, | ||
# even in these small test examples: | ||
sc = SparkContext("local[2]", "ml.feature tests") | ||
sqlCtx = SQLContext(sc) | ||
globs['sc'] = sc | ||
globs['sqlCtx'] = sqlCtx | ||
(failure_count, test_count) = doctest.testmod( | ||
globs=globs, optionflags=doctest.ELLIPSIS) | ||
sc.stop() | ||
if failure_count: | ||
exit(-1) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This looks very Java style, verbose and many lines, imaged that could be simplified as :