Skip to content
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
wants to merge 34 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
33b68e0
a working LR
mengxr Dec 23, 2014
46eea43
a pipeline in python
mengxr Dec 31, 2014
a3015cf
add Estimator and Transformer
mengxr Dec 31, 2014
dadd84e
add base classes and docs
mengxr Jan 19, 2015
c18dca1
make the example working
mengxr Jan 19, 2015
d9ea77c
update doc
mengxr Jan 19, 2015
17ecfb9
code gen for shared params
mengxr Jan 21, 2015
bce72f4
Merge remote-tracking branch 'apache/master' into SPARK-4586
mengxr Jan 21, 2015
d0c5bb8
a working copy
mengxr Jan 22, 2015
56de571
fix style
mengxr Jan 22, 2015
d3e8dbe
more docs
mengxr Jan 26, 2015
05e3e40
update example
mengxr Jan 26, 2015
f4d0fe6
use LabeledDocument and Document in example
mengxr Jan 27, 2015
d5efd34
update doc conf and move embedded param map to instance attribute
mengxr Jan 27, 2015
f66ba0c
make params a property
mengxr Jan 27, 2015
1dcc17e
update code gen and make param appear in the doc
mengxr Jan 27, 2015
46fa147
update mllib/pom.xml to include python files in the assembly
mengxr Jan 27, 2015
036ca04
gen numFeatures
mengxr Jan 27, 2015
5153cff
simplify java models
mengxr Jan 27, 2015
0586c7b
add more comments to the example
mengxr Jan 27, 2015
ba0ba1e
add unit tests for pipeline
mengxr Jan 27, 2015
7521d1c
add unit tests to HashingTF and Tokenizer
mengxr Jan 27, 2015
a4f4dbf
add unit test for LR
mengxr Jan 27, 2015
0882513
update doc style
mengxr Jan 27, 2015
090b3a3
Merge branch 'master' of github.com:apache/spark into ml
Jan 28, 2015
1dca16a
refactor
Jan 28, 2015
fc59a02
Merge remote-tracking branch 'apache/master' into SPARK-4586
mengxr Jan 28, 2015
78638df
Merge branch 'SPARK-4586' of github.com:mengxr/spark into ml
Jan 28, 2015
54ca7df
fix tests
Jan 28, 2015
14ae7e2
fix docs
Jan 28, 2015
dd1256b
Merge remote-tracking branch 'apache/master' into SPARK-4586
mengxr Jan 28, 2015
44c2405
Merge pull request #2 from davies/ml
mengxr Jan 28, 2015
edbd6fe
move Identifiable to ml.util
mengxr Jan 28, 2015
415268e
remove inherit_doc from __init__
mengxr Jan 28, 2015
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions examples/src/main/python/ml/simple_text_classification_pipeline.py
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])
Copy link
Contributor

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 :

tokenizer = Tokenizer("text", "words")
hashingTF = HashingTF("words", "features")
lr = LogisticRegression(maxIter=10, regParam=0.01)
pipeline = Pipeline([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()
2 changes: 2 additions & 0 deletions mllib/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,8 @@
<directory>../python</directory>
<includes>
<include>pyspark/mllib/*.py</include>
<include>pyspark/ml/*.py</include>
<include>pyspark/ml/param/*.py</include>
</includes>
</resource>
</resources>
Expand Down
8 changes: 7 additions & 1 deletion mllib/src/main/scala/org/apache/spark/ml/param/params.scala
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,13 @@ trait Params extends Identifiable with Serializable {
this
}

/**
* Sets a parameter (by name) in the embedded param map.
*/
private[ml] def set(param: String, value: Any): this.type = {
set(getParam(param), value)
}

/**
* Gets the value of a parameter in the embedded param map.
*/
Expand Down Expand Up @@ -286,7 +293,6 @@ class ParamMap private[ml] (private val map: mutable.Map[Param[Any], Any]) exten
new ParamMap(this.map ++ other.map)
}


/**
* Adds all parameters from the input param map into this param map.
*/
Expand Down
4 changes: 2 additions & 2 deletions python/docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,9 @@
# built documents.
#
# The short X.Y version.
version = '1.2-SNAPSHOT'
version = '1.3-SNAPSHOT'
# The full version, including alpha/beta/rc tags.
release = '1.2-SNAPSHOT'
release = '1.3-SNAPSHOT'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
Expand Down
1 change: 1 addition & 0 deletions python/docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Contents:
pyspark
pyspark.sql
pyspark.streaming
pyspark.ml
pyspark.mllib


Expand Down
29 changes: 29 additions & 0 deletions python/docs/pyspark.ml.rst
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:
1 change: 1 addition & 0 deletions python/docs/pyspark.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Subpackages

pyspark.sql
pyspark.streaming
pyspark.ml
pyspark.mllib

Contents
Expand Down
21 changes: 21 additions & 0 deletions python/pyspark/ml/__init__.py
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"]
76 changes: 76 additions & 0 deletions python/pyspark/ml/classification.py
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)
82 changes: 82 additions & 0 deletions python/pyspark/ml/feature.py
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)
Loading