2015-01-28 20:14:23 -05:00
|
|
|
#
|
|
|
|
# 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.
|
|
|
|
#
|
|
|
|
|
2015-02-20 05:31:32 -05:00
|
|
|
from pyspark.ml.util import keyword_only
|
2015-01-28 20:14:23 -05:00
|
|
|
from pyspark.ml.wrapper import JavaEstimator, JavaModel
|
2015-05-13 18:13:09 -04:00
|
|
|
from pyspark.ml.param.shared import *
|
2015-07-07 11:58:08 -04:00
|
|
|
from pyspark.ml.regression import (
|
|
|
|
RandomForestParams, DecisionTreeModel, TreeEnsembleModels)
|
2015-02-20 05:31:32 -05:00
|
|
|
from pyspark.mllib.common import inherit_doc
|
2015-01-28 20:14:23 -05:00
|
|
|
|
|
|
|
|
2015-05-13 18:13:09 -04:00
|
|
|
__all__ = ['LogisticRegression', 'LogisticRegressionModel', 'DecisionTreeClassifier',
|
|
|
|
'DecisionTreeClassificationModel', 'GBTClassifier', 'GBTClassificationModel',
|
2015-07-31 02:03:48 -04:00
|
|
|
'RandomForestClassifier', 'RandomForestClassificationModel', 'NaiveBayes',
|
|
|
|
'NaiveBayesModel']
|
2015-01-28 20:14:23 -05:00
|
|
|
|
|
|
|
|
|
|
|
@inherit_doc
|
|
|
|
class LogisticRegression(JavaEstimator, HasFeaturesCol, HasLabelCol, HasPredictionCol, HasMaxIter,
|
2015-08-03 01:19:27 -04:00
|
|
|
HasRegParam, HasTol, HasProbabilityCol, HasRawPredictionCol):
|
2015-01-28 20:14:23 -05:00
|
|
|
"""
|
|
|
|
Logistic regression.
|
|
|
|
|
|
|
|
>>> from pyspark.sql import Row
|
|
|
|
>>> from pyspark.mllib.linalg import Vectors
|
2015-02-15 23:29:26 -05:00
|
|
|
>>> df = sc.parallelize([
|
|
|
|
... Row(label=1.0, features=Vectors.dense(1.0)),
|
|
|
|
... Row(label=0.0, features=Vectors.sparse(1, [], []))]).toDF()
|
|
|
|
>>> lr = LogisticRegression(maxIter=5, regParam=0.01)
|
|
|
|
>>> model = lr.fit(df)
|
2015-05-14 21:13:58 -04:00
|
|
|
>>> model.weights
|
|
|
|
DenseVector([5.5...])
|
|
|
|
>>> model.intercept
|
|
|
|
-2.68...
|
2015-08-03 01:19:27 -04:00
|
|
|
>>> test0 = sc.parallelize([Row(features=Vectors.dense(-1.0))]).toDF()
|
|
|
|
>>> result = model.transform(test0).head()
|
|
|
|
>>> result.prediction
|
|
|
|
0.0
|
|
|
|
>>> result.probability
|
|
|
|
DenseVector([0.99..., 0.00...])
|
|
|
|
>>> result.rawPrediction
|
|
|
|
DenseVector([8.22..., -8.22...])
|
2015-02-15 23:29:26 -05:00
|
|
|
>>> test1 = sc.parallelize([Row(features=Vectors.sparse(1, [0], [1.0]))]).toDF()
|
2015-04-16 19:20:57 -04:00
|
|
|
>>> model.transform(test1).head().prediction
|
2015-01-28 20:14:23 -05:00
|
|
|
1.0
|
2015-02-15 23:29:26 -05:00
|
|
|
>>> lr.setParams("vector")
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
TypeError: Method setParams forces keyword arguments.
|
2015-01-28 20:14:23 -05:00
|
|
|
"""
|
2015-05-18 15:02:18 -04:00
|
|
|
|
2015-05-13 18:13:09 -04:00
|
|
|
# a placeholder to make it appear in the generated doc
|
|
|
|
elasticNetParam = \
|
|
|
|
Param(Params._dummy(), "elasticNetParam",
|
|
|
|
"the ElasticNet mixing parameter, in range [0, 1]. For alpha = 0, " +
|
|
|
|
"the penalty is an L2 penalty. For alpha = 1, it is an L1 penalty.")
|
|
|
|
fitIntercept = Param(Params._dummy(), "fitIntercept", "whether to fit an intercept term.")
|
[SPARK-8069] [ML] Add multiclass thresholds for ProbabilisticClassifier
This PR replaces the old "threshold" with a generalized "thresholds" Param. We keep getThreshold,setThreshold for backwards compatibility for binary classification.
Note that the primary author of this PR is holdenk
Author: Holden Karau <holden@pigscanfly.ca>
Author: Joseph K. Bradley <joseph@databricks.com>
Closes #7909 from jkbradley/holdenk-SPARK-8069-add-cutoff-aka-threshold-to-random-forest and squashes the following commits:
3952977 [Joseph K. Bradley] fixed pyspark doc test
85febc8 [Joseph K. Bradley] made python unit tests a little more robust
7eb1d86 [Joseph K. Bradley] small cleanups
6cc2ed8 [Joseph K. Bradley] Fixed remaining merge issues.
0255e44 [Joseph K. Bradley] Many cleanups for thresholds, some more tests
7565a60 [Holden Karau] fix pep8 style checks, add a getThreshold method similar to our LogisticRegression.scala one for API compat
be87f26 [Holden Karau] Convert threshold to thresholds in the python code, add specialized support for Array[Double] to shared parems codegen, etc.
6747dad [Holden Karau] Override raw2prediction for ProbabilisticClassifier, fix some tests
25df168 [Holden Karau] Fix handling of thresholds in LogisticRegression
c02d6c0 [Holden Karau] No default for thresholds
5e43628 [Holden Karau] CR feedback and fixed the renamed test
f3fbbd1 [Holden Karau] revert the changes to random forest :(
51f581c [Holden Karau] Add explicit types to public methods, fix long line
f7032eb [Holden Karau] Fix a java test bug, remove some unecessary changes
adf15b4 [Holden Karau] rename the classifier suite test to ProbabilisticClassifierSuite now that we only have it in Probabilistic
398078a [Holden Karau] move the thresholding around a bunch based on the design doc
4893bdc [Holden Karau] Use numtrees of 3 since previous result was tied (one tree for each) and the switch from different max methods picked a different element (since they were equal I think this is ok)
638854c [Holden Karau] Add a scala RandomForestClassifierSuite test based on corresponding python test
e09919c [Holden Karau] Fix return type, I need more coffee....
8d92cac [Holden Karau] Use ClassifierParams as the head
3456ed3 [Holden Karau] Add explicit return types even though just test
a0f3b0c [Holden Karau] scala style fixes
6f14314 [Holden Karau] Since hasthreshold/hasthresholds is in root classifier now
ffc8dab [Holden Karau] Update the sharedParams
0420290 [Holden Karau] Allow us to override the get methods selectively
978e77a [Holden Karau] Move HasThreshold into classifier params and start defining the overloaded getThreshold/getThresholds functions
1433e52 [Holden Karau] Revert "try and hide threshold but chainges the API so no dice there"
1f09a2e [Holden Karau] try and hide threshold but chainges the API so no dice there
efb9084 [Holden Karau] move setThresholds only to where its used
6b34809 [Holden Karau] Add a test with thresholding for the RFCS
74f54c3 [Holden Karau] Fix creation of vote array
1986fa8 [Holden Karau] Setting the thresholds only makes sense if the underlying class hasn't overridden predict, so lets push it down.
2f44b18 [Holden Karau] Add a global default of null for thresholds param
f338cfc [Holden Karau] Wait that wasn't a good idea, Revert "Some progress towards unifying threshold and thresholds"
634b06f [Holden Karau] Some progress towards unifying threshold and thresholds
85c9e01 [Holden Karau] Test passes again... little fnur
099c0f3 [Holden Karau] Move thresholds around some more (set on model not trainer)
0f46836 [Holden Karau] Start adding a classifiersuite
f70eb5e [Holden Karau] Fix test compile issues
a7d59c8 [Holden Karau] Move thresholding into Classifier trait
5d999d2 [Holden Karau] Some more progress, start adding a test (maybe try and see if we can find a better thing to use for the base of the test)
1fed644 [Holden Karau] Use thresholds to scale scores in random forest classifcation
31d6bf2 [Holden Karau] Start threading the threshold info through
0ef228c [Holden Karau] Add hasthresholds
2015-08-04 13:12:22 -04:00
|
|
|
thresholds = Param(Params._dummy(), "thresholds",
|
|
|
|
"Thresholds in multi-class classification" +
|
|
|
|
" to adjust the probability of predicting each class." +
|
|
|
|
" Array must have length equal to the number of classes, with values >= 0." +
|
|
|
|
" The class with largest value p/t is predicted, where p is the original" +
|
|
|
|
" probability of that class and t is the class' threshold.")
|
2015-01-28 20:14:23 -05:00
|
|
|
|
2015-02-15 23:29:26 -05:00
|
|
|
@keyword_only
|
|
|
|
def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction",
|
2015-05-13 18:13:09 -04:00
|
|
|
maxIter=100, regParam=0.1, elasticNetParam=0.0, tol=1e-6, fitIntercept=True,
|
[SPARK-8069] [ML] Add multiclass thresholds for ProbabilisticClassifier
This PR replaces the old "threshold" with a generalized "thresholds" Param. We keep getThreshold,setThreshold for backwards compatibility for binary classification.
Note that the primary author of this PR is holdenk
Author: Holden Karau <holden@pigscanfly.ca>
Author: Joseph K. Bradley <joseph@databricks.com>
Closes #7909 from jkbradley/holdenk-SPARK-8069-add-cutoff-aka-threshold-to-random-forest and squashes the following commits:
3952977 [Joseph K. Bradley] fixed pyspark doc test
85febc8 [Joseph K. Bradley] made python unit tests a little more robust
7eb1d86 [Joseph K. Bradley] small cleanups
6cc2ed8 [Joseph K. Bradley] Fixed remaining merge issues.
0255e44 [Joseph K. Bradley] Many cleanups for thresholds, some more tests
7565a60 [Holden Karau] fix pep8 style checks, add a getThreshold method similar to our LogisticRegression.scala one for API compat
be87f26 [Holden Karau] Convert threshold to thresholds in the python code, add specialized support for Array[Double] to shared parems codegen, etc.
6747dad [Holden Karau] Override raw2prediction for ProbabilisticClassifier, fix some tests
25df168 [Holden Karau] Fix handling of thresholds in LogisticRegression
c02d6c0 [Holden Karau] No default for thresholds
5e43628 [Holden Karau] CR feedback and fixed the renamed test
f3fbbd1 [Holden Karau] revert the changes to random forest :(
51f581c [Holden Karau] Add explicit types to public methods, fix long line
f7032eb [Holden Karau] Fix a java test bug, remove some unecessary changes
adf15b4 [Holden Karau] rename the classifier suite test to ProbabilisticClassifierSuite now that we only have it in Probabilistic
398078a [Holden Karau] move the thresholding around a bunch based on the design doc
4893bdc [Holden Karau] Use numtrees of 3 since previous result was tied (one tree for each) and the switch from different max methods picked a different element (since they were equal I think this is ok)
638854c [Holden Karau] Add a scala RandomForestClassifierSuite test based on corresponding python test
e09919c [Holden Karau] Fix return type, I need more coffee....
8d92cac [Holden Karau] Use ClassifierParams as the head
3456ed3 [Holden Karau] Add explicit return types even though just test
a0f3b0c [Holden Karau] scala style fixes
6f14314 [Holden Karau] Since hasthreshold/hasthresholds is in root classifier now
ffc8dab [Holden Karau] Update the sharedParams
0420290 [Holden Karau] Allow us to override the get methods selectively
978e77a [Holden Karau] Move HasThreshold into classifier params and start defining the overloaded getThreshold/getThresholds functions
1433e52 [Holden Karau] Revert "try and hide threshold but chainges the API so no dice there"
1f09a2e [Holden Karau] try and hide threshold but chainges the API so no dice there
efb9084 [Holden Karau] move setThresholds only to where its used
6b34809 [Holden Karau] Add a test with thresholding for the RFCS
74f54c3 [Holden Karau] Fix creation of vote array
1986fa8 [Holden Karau] Setting the thresholds only makes sense if the underlying class hasn't overridden predict, so lets push it down.
2f44b18 [Holden Karau] Add a global default of null for thresholds param
f338cfc [Holden Karau] Wait that wasn't a good idea, Revert "Some progress towards unifying threshold and thresholds"
634b06f [Holden Karau] Some progress towards unifying threshold and thresholds
85c9e01 [Holden Karau] Test passes again... little fnur
099c0f3 [Holden Karau] Move thresholds around some more (set on model not trainer)
0f46836 [Holden Karau] Start adding a classifiersuite
f70eb5e [Holden Karau] Fix test compile issues
a7d59c8 [Holden Karau] Move thresholding into Classifier trait
5d999d2 [Holden Karau] Some more progress, start adding a test (maybe try and see if we can find a better thing to use for the base of the test)
1fed644 [Holden Karau] Use thresholds to scale scores in random forest classifcation
31d6bf2 [Holden Karau] Start threading the threshold info through
0ef228c [Holden Karau] Add hasthresholds
2015-08-04 13:12:22 -04:00
|
|
|
threshold=None, thresholds=None,
|
|
|
|
probabilityCol="probability", rawPredictionCol="rawPrediction"):
|
2015-02-15 23:29:26 -05:00
|
|
|
"""
|
|
|
|
__init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
|
2015-05-14 21:16:22 -04:00
|
|
|
maxIter=100, regParam=0.1, elasticNetParam=0.0, tol=1e-6, fitIntercept=True, \
|
[SPARK-8069] [ML] Add multiclass thresholds for ProbabilisticClassifier
This PR replaces the old "threshold" with a generalized "thresholds" Param. We keep getThreshold,setThreshold for backwards compatibility for binary classification.
Note that the primary author of this PR is holdenk
Author: Holden Karau <holden@pigscanfly.ca>
Author: Joseph K. Bradley <joseph@databricks.com>
Closes #7909 from jkbradley/holdenk-SPARK-8069-add-cutoff-aka-threshold-to-random-forest and squashes the following commits:
3952977 [Joseph K. Bradley] fixed pyspark doc test
85febc8 [Joseph K. Bradley] made python unit tests a little more robust
7eb1d86 [Joseph K. Bradley] small cleanups
6cc2ed8 [Joseph K. Bradley] Fixed remaining merge issues.
0255e44 [Joseph K. Bradley] Many cleanups for thresholds, some more tests
7565a60 [Holden Karau] fix pep8 style checks, add a getThreshold method similar to our LogisticRegression.scala one for API compat
be87f26 [Holden Karau] Convert threshold to thresholds in the python code, add specialized support for Array[Double] to shared parems codegen, etc.
6747dad [Holden Karau] Override raw2prediction for ProbabilisticClassifier, fix some tests
25df168 [Holden Karau] Fix handling of thresholds in LogisticRegression
c02d6c0 [Holden Karau] No default for thresholds
5e43628 [Holden Karau] CR feedback and fixed the renamed test
f3fbbd1 [Holden Karau] revert the changes to random forest :(
51f581c [Holden Karau] Add explicit types to public methods, fix long line
f7032eb [Holden Karau] Fix a java test bug, remove some unecessary changes
adf15b4 [Holden Karau] rename the classifier suite test to ProbabilisticClassifierSuite now that we only have it in Probabilistic
398078a [Holden Karau] move the thresholding around a bunch based on the design doc
4893bdc [Holden Karau] Use numtrees of 3 since previous result was tied (one tree for each) and the switch from different max methods picked a different element (since they were equal I think this is ok)
638854c [Holden Karau] Add a scala RandomForestClassifierSuite test based on corresponding python test
e09919c [Holden Karau] Fix return type, I need more coffee....
8d92cac [Holden Karau] Use ClassifierParams as the head
3456ed3 [Holden Karau] Add explicit return types even though just test
a0f3b0c [Holden Karau] scala style fixes
6f14314 [Holden Karau] Since hasthreshold/hasthresholds is in root classifier now
ffc8dab [Holden Karau] Update the sharedParams
0420290 [Holden Karau] Allow us to override the get methods selectively
978e77a [Holden Karau] Move HasThreshold into classifier params and start defining the overloaded getThreshold/getThresholds functions
1433e52 [Holden Karau] Revert "try and hide threshold but chainges the API so no dice there"
1f09a2e [Holden Karau] try and hide threshold but chainges the API so no dice there
efb9084 [Holden Karau] move setThresholds only to where its used
6b34809 [Holden Karau] Add a test with thresholding for the RFCS
74f54c3 [Holden Karau] Fix creation of vote array
1986fa8 [Holden Karau] Setting the thresholds only makes sense if the underlying class hasn't overridden predict, so lets push it down.
2f44b18 [Holden Karau] Add a global default of null for thresholds param
f338cfc [Holden Karau] Wait that wasn't a good idea, Revert "Some progress towards unifying threshold and thresholds"
634b06f [Holden Karau] Some progress towards unifying threshold and thresholds
85c9e01 [Holden Karau] Test passes again... little fnur
099c0f3 [Holden Karau] Move thresholds around some more (set on model not trainer)
0f46836 [Holden Karau] Start adding a classifiersuite
f70eb5e [Holden Karau] Fix test compile issues
a7d59c8 [Holden Karau] Move thresholding into Classifier trait
5d999d2 [Holden Karau] Some more progress, start adding a test (maybe try and see if we can find a better thing to use for the base of the test)
1fed644 [Holden Karau] Use thresholds to scale scores in random forest classifcation
31d6bf2 [Holden Karau] Start threading the threshold info through
0ef228c [Holden Karau] Add hasthresholds
2015-08-04 13:12:22 -04:00
|
|
|
threshold=None, thresholds=None, \
|
|
|
|
probabilityCol="probability", rawPredictionCol="rawPrediction")
|
|
|
|
Param thresholds overrides Param threshold; threshold is provided
|
|
|
|
for backwards compatibility and only applies to binary classification.
|
2015-02-15 23:29:26 -05:00
|
|
|
"""
|
|
|
|
super(LogisticRegression, self).__init__()
|
2015-05-18 15:02:18 -04:00
|
|
|
self._java_obj = self._new_java_obj(
|
|
|
|
"org.apache.spark.ml.classification.LogisticRegression", self.uid)
|
2015-05-13 18:13:09 -04:00
|
|
|
#: param for the ElasticNet mixing parameter, in range [0, 1]. For alpha = 0, the penalty
|
|
|
|
# is an L2 penalty. For alpha = 1, it is an L1 penalty.
|
|
|
|
self.elasticNetParam = \
|
|
|
|
Param(self, "elasticNetParam",
|
|
|
|
"the ElasticNet mixing parameter, in range [0, 1]. For alpha = 0, the penalty " +
|
|
|
|
"is an L2 penalty. For alpha = 1, it is an L1 penalty.")
|
|
|
|
#: param for whether to fit an intercept term.
|
|
|
|
self.fitIntercept = Param(self, "fitIntercept", "whether to fit an intercept term.")
|
|
|
|
#: param for threshold in binary classification prediction, in range [0, 1].
|
[SPARK-8069] [ML] Add multiclass thresholds for ProbabilisticClassifier
This PR replaces the old "threshold" with a generalized "thresholds" Param. We keep getThreshold,setThreshold for backwards compatibility for binary classification.
Note that the primary author of this PR is holdenk
Author: Holden Karau <holden@pigscanfly.ca>
Author: Joseph K. Bradley <joseph@databricks.com>
Closes #7909 from jkbradley/holdenk-SPARK-8069-add-cutoff-aka-threshold-to-random-forest and squashes the following commits:
3952977 [Joseph K. Bradley] fixed pyspark doc test
85febc8 [Joseph K. Bradley] made python unit tests a little more robust
7eb1d86 [Joseph K. Bradley] small cleanups
6cc2ed8 [Joseph K. Bradley] Fixed remaining merge issues.
0255e44 [Joseph K. Bradley] Many cleanups for thresholds, some more tests
7565a60 [Holden Karau] fix pep8 style checks, add a getThreshold method similar to our LogisticRegression.scala one for API compat
be87f26 [Holden Karau] Convert threshold to thresholds in the python code, add specialized support for Array[Double] to shared parems codegen, etc.
6747dad [Holden Karau] Override raw2prediction for ProbabilisticClassifier, fix some tests
25df168 [Holden Karau] Fix handling of thresholds in LogisticRegression
c02d6c0 [Holden Karau] No default for thresholds
5e43628 [Holden Karau] CR feedback and fixed the renamed test
f3fbbd1 [Holden Karau] revert the changes to random forest :(
51f581c [Holden Karau] Add explicit types to public methods, fix long line
f7032eb [Holden Karau] Fix a java test bug, remove some unecessary changes
adf15b4 [Holden Karau] rename the classifier suite test to ProbabilisticClassifierSuite now that we only have it in Probabilistic
398078a [Holden Karau] move the thresholding around a bunch based on the design doc
4893bdc [Holden Karau] Use numtrees of 3 since previous result was tied (one tree for each) and the switch from different max methods picked a different element (since they were equal I think this is ok)
638854c [Holden Karau] Add a scala RandomForestClassifierSuite test based on corresponding python test
e09919c [Holden Karau] Fix return type, I need more coffee....
8d92cac [Holden Karau] Use ClassifierParams as the head
3456ed3 [Holden Karau] Add explicit return types even though just test
a0f3b0c [Holden Karau] scala style fixes
6f14314 [Holden Karau] Since hasthreshold/hasthresholds is in root classifier now
ffc8dab [Holden Karau] Update the sharedParams
0420290 [Holden Karau] Allow us to override the get methods selectively
978e77a [Holden Karau] Move HasThreshold into classifier params and start defining the overloaded getThreshold/getThresholds functions
1433e52 [Holden Karau] Revert "try and hide threshold but chainges the API so no dice there"
1f09a2e [Holden Karau] try and hide threshold but chainges the API so no dice there
efb9084 [Holden Karau] move setThresholds only to where its used
6b34809 [Holden Karau] Add a test with thresholding for the RFCS
74f54c3 [Holden Karau] Fix creation of vote array
1986fa8 [Holden Karau] Setting the thresholds only makes sense if the underlying class hasn't overridden predict, so lets push it down.
2f44b18 [Holden Karau] Add a global default of null for thresholds param
f338cfc [Holden Karau] Wait that wasn't a good idea, Revert "Some progress towards unifying threshold and thresholds"
634b06f [Holden Karau] Some progress towards unifying threshold and thresholds
85c9e01 [Holden Karau] Test passes again... little fnur
099c0f3 [Holden Karau] Move thresholds around some more (set on model not trainer)
0f46836 [Holden Karau] Start adding a classifiersuite
f70eb5e [Holden Karau] Fix test compile issues
a7d59c8 [Holden Karau] Move thresholding into Classifier trait
5d999d2 [Holden Karau] Some more progress, start adding a test (maybe try and see if we can find a better thing to use for the base of the test)
1fed644 [Holden Karau] Use thresholds to scale scores in random forest classifcation
31d6bf2 [Holden Karau] Start threading the threshold info through
0ef228c [Holden Karau] Add hasthresholds
2015-08-04 13:12:22 -04:00
|
|
|
self.thresholds = \
|
|
|
|
Param(self, "thresholds",
|
|
|
|
"Thresholds in multi-class classification" +
|
|
|
|
" to adjust the probability of predicting each class." +
|
|
|
|
" Array must have length equal to the number of classes, with values >= 0." +
|
|
|
|
" The class with largest value p/t is predicted, where p is the original" +
|
|
|
|
" probability of that class and t is the class' threshold.")
|
2015-05-13 18:13:09 -04:00
|
|
|
self._setDefault(maxIter=100, regParam=0.1, elasticNetParam=0.0, tol=1E-6,
|
[SPARK-8069] [ML] Add multiclass thresholds for ProbabilisticClassifier
This PR replaces the old "threshold" with a generalized "thresholds" Param. We keep getThreshold,setThreshold for backwards compatibility for binary classification.
Note that the primary author of this PR is holdenk
Author: Holden Karau <holden@pigscanfly.ca>
Author: Joseph K. Bradley <joseph@databricks.com>
Closes #7909 from jkbradley/holdenk-SPARK-8069-add-cutoff-aka-threshold-to-random-forest and squashes the following commits:
3952977 [Joseph K. Bradley] fixed pyspark doc test
85febc8 [Joseph K. Bradley] made python unit tests a little more robust
7eb1d86 [Joseph K. Bradley] small cleanups
6cc2ed8 [Joseph K. Bradley] Fixed remaining merge issues.
0255e44 [Joseph K. Bradley] Many cleanups for thresholds, some more tests
7565a60 [Holden Karau] fix pep8 style checks, add a getThreshold method similar to our LogisticRegression.scala one for API compat
be87f26 [Holden Karau] Convert threshold to thresholds in the python code, add specialized support for Array[Double] to shared parems codegen, etc.
6747dad [Holden Karau] Override raw2prediction for ProbabilisticClassifier, fix some tests
25df168 [Holden Karau] Fix handling of thresholds in LogisticRegression
c02d6c0 [Holden Karau] No default for thresholds
5e43628 [Holden Karau] CR feedback and fixed the renamed test
f3fbbd1 [Holden Karau] revert the changes to random forest :(
51f581c [Holden Karau] Add explicit types to public methods, fix long line
f7032eb [Holden Karau] Fix a java test bug, remove some unecessary changes
adf15b4 [Holden Karau] rename the classifier suite test to ProbabilisticClassifierSuite now that we only have it in Probabilistic
398078a [Holden Karau] move the thresholding around a bunch based on the design doc
4893bdc [Holden Karau] Use numtrees of 3 since previous result was tied (one tree for each) and the switch from different max methods picked a different element (since they were equal I think this is ok)
638854c [Holden Karau] Add a scala RandomForestClassifierSuite test based on corresponding python test
e09919c [Holden Karau] Fix return type, I need more coffee....
8d92cac [Holden Karau] Use ClassifierParams as the head
3456ed3 [Holden Karau] Add explicit return types even though just test
a0f3b0c [Holden Karau] scala style fixes
6f14314 [Holden Karau] Since hasthreshold/hasthresholds is in root classifier now
ffc8dab [Holden Karau] Update the sharedParams
0420290 [Holden Karau] Allow us to override the get methods selectively
978e77a [Holden Karau] Move HasThreshold into classifier params and start defining the overloaded getThreshold/getThresholds functions
1433e52 [Holden Karau] Revert "try and hide threshold but chainges the API so no dice there"
1f09a2e [Holden Karau] try and hide threshold but chainges the API so no dice there
efb9084 [Holden Karau] move setThresholds only to where its used
6b34809 [Holden Karau] Add a test with thresholding for the RFCS
74f54c3 [Holden Karau] Fix creation of vote array
1986fa8 [Holden Karau] Setting the thresholds only makes sense if the underlying class hasn't overridden predict, so lets push it down.
2f44b18 [Holden Karau] Add a global default of null for thresholds param
f338cfc [Holden Karau] Wait that wasn't a good idea, Revert "Some progress towards unifying threshold and thresholds"
634b06f [Holden Karau] Some progress towards unifying threshold and thresholds
85c9e01 [Holden Karau] Test passes again... little fnur
099c0f3 [Holden Karau] Move thresholds around some more (set on model not trainer)
0f46836 [Holden Karau] Start adding a classifiersuite
f70eb5e [Holden Karau] Fix test compile issues
a7d59c8 [Holden Karau] Move thresholding into Classifier trait
5d999d2 [Holden Karau] Some more progress, start adding a test (maybe try and see if we can find a better thing to use for the base of the test)
1fed644 [Holden Karau] Use thresholds to scale scores in random forest classifcation
31d6bf2 [Holden Karau] Start threading the threshold info through
0ef228c [Holden Karau] Add hasthresholds
2015-08-04 13:12:22 -04:00
|
|
|
fitIntercept=True)
|
2015-02-15 23:29:26 -05:00
|
|
|
kwargs = self.__init__._input_kwargs
|
|
|
|
self.setParams(**kwargs)
|
|
|
|
|
|
|
|
@keyword_only
|
|
|
|
def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction",
|
2015-05-13 18:13:09 -04:00
|
|
|
maxIter=100, regParam=0.1, elasticNetParam=0.0, tol=1e-6, fitIntercept=True,
|
[SPARK-8069] [ML] Add multiclass thresholds for ProbabilisticClassifier
This PR replaces the old "threshold" with a generalized "thresholds" Param. We keep getThreshold,setThreshold for backwards compatibility for binary classification.
Note that the primary author of this PR is holdenk
Author: Holden Karau <holden@pigscanfly.ca>
Author: Joseph K. Bradley <joseph@databricks.com>
Closes #7909 from jkbradley/holdenk-SPARK-8069-add-cutoff-aka-threshold-to-random-forest and squashes the following commits:
3952977 [Joseph K. Bradley] fixed pyspark doc test
85febc8 [Joseph K. Bradley] made python unit tests a little more robust
7eb1d86 [Joseph K. Bradley] small cleanups
6cc2ed8 [Joseph K. Bradley] Fixed remaining merge issues.
0255e44 [Joseph K. Bradley] Many cleanups for thresholds, some more tests
7565a60 [Holden Karau] fix pep8 style checks, add a getThreshold method similar to our LogisticRegression.scala one for API compat
be87f26 [Holden Karau] Convert threshold to thresholds in the python code, add specialized support for Array[Double] to shared parems codegen, etc.
6747dad [Holden Karau] Override raw2prediction for ProbabilisticClassifier, fix some tests
25df168 [Holden Karau] Fix handling of thresholds in LogisticRegression
c02d6c0 [Holden Karau] No default for thresholds
5e43628 [Holden Karau] CR feedback and fixed the renamed test
f3fbbd1 [Holden Karau] revert the changes to random forest :(
51f581c [Holden Karau] Add explicit types to public methods, fix long line
f7032eb [Holden Karau] Fix a java test bug, remove some unecessary changes
adf15b4 [Holden Karau] rename the classifier suite test to ProbabilisticClassifierSuite now that we only have it in Probabilistic
398078a [Holden Karau] move the thresholding around a bunch based on the design doc
4893bdc [Holden Karau] Use numtrees of 3 since previous result was tied (one tree for each) and the switch from different max methods picked a different element (since they were equal I think this is ok)
638854c [Holden Karau] Add a scala RandomForestClassifierSuite test based on corresponding python test
e09919c [Holden Karau] Fix return type, I need more coffee....
8d92cac [Holden Karau] Use ClassifierParams as the head
3456ed3 [Holden Karau] Add explicit return types even though just test
a0f3b0c [Holden Karau] scala style fixes
6f14314 [Holden Karau] Since hasthreshold/hasthresholds is in root classifier now
ffc8dab [Holden Karau] Update the sharedParams
0420290 [Holden Karau] Allow us to override the get methods selectively
978e77a [Holden Karau] Move HasThreshold into classifier params and start defining the overloaded getThreshold/getThresholds functions
1433e52 [Holden Karau] Revert "try and hide threshold but chainges the API so no dice there"
1f09a2e [Holden Karau] try and hide threshold but chainges the API so no dice there
efb9084 [Holden Karau] move setThresholds only to where its used
6b34809 [Holden Karau] Add a test with thresholding for the RFCS
74f54c3 [Holden Karau] Fix creation of vote array
1986fa8 [Holden Karau] Setting the thresholds only makes sense if the underlying class hasn't overridden predict, so lets push it down.
2f44b18 [Holden Karau] Add a global default of null for thresholds param
f338cfc [Holden Karau] Wait that wasn't a good idea, Revert "Some progress towards unifying threshold and thresholds"
634b06f [Holden Karau] Some progress towards unifying threshold and thresholds
85c9e01 [Holden Karau] Test passes again... little fnur
099c0f3 [Holden Karau] Move thresholds around some more (set on model not trainer)
0f46836 [Holden Karau] Start adding a classifiersuite
f70eb5e [Holden Karau] Fix test compile issues
a7d59c8 [Holden Karau] Move thresholding into Classifier trait
5d999d2 [Holden Karau] Some more progress, start adding a test (maybe try and see if we can find a better thing to use for the base of the test)
1fed644 [Holden Karau] Use thresholds to scale scores in random forest classifcation
31d6bf2 [Holden Karau] Start threading the threshold info through
0ef228c [Holden Karau] Add hasthresholds
2015-08-04 13:12:22 -04:00
|
|
|
threshold=None, thresholds=None,
|
|
|
|
probabilityCol="probability", rawPredictionCol="rawPrediction"):
|
2015-02-15 23:29:26 -05:00
|
|
|
"""
|
2015-05-14 21:16:22 -04:00
|
|
|
setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
|
|
|
|
maxIter=100, regParam=0.1, elasticNetParam=0.0, tol=1e-6, fitIntercept=True, \
|
[SPARK-8069] [ML] Add multiclass thresholds for ProbabilisticClassifier
This PR replaces the old "threshold" with a generalized "thresholds" Param. We keep getThreshold,setThreshold for backwards compatibility for binary classification.
Note that the primary author of this PR is holdenk
Author: Holden Karau <holden@pigscanfly.ca>
Author: Joseph K. Bradley <joseph@databricks.com>
Closes #7909 from jkbradley/holdenk-SPARK-8069-add-cutoff-aka-threshold-to-random-forest and squashes the following commits:
3952977 [Joseph K. Bradley] fixed pyspark doc test
85febc8 [Joseph K. Bradley] made python unit tests a little more robust
7eb1d86 [Joseph K. Bradley] small cleanups
6cc2ed8 [Joseph K. Bradley] Fixed remaining merge issues.
0255e44 [Joseph K. Bradley] Many cleanups for thresholds, some more tests
7565a60 [Holden Karau] fix pep8 style checks, add a getThreshold method similar to our LogisticRegression.scala one for API compat
be87f26 [Holden Karau] Convert threshold to thresholds in the python code, add specialized support for Array[Double] to shared parems codegen, etc.
6747dad [Holden Karau] Override raw2prediction for ProbabilisticClassifier, fix some tests
25df168 [Holden Karau] Fix handling of thresholds in LogisticRegression
c02d6c0 [Holden Karau] No default for thresholds
5e43628 [Holden Karau] CR feedback and fixed the renamed test
f3fbbd1 [Holden Karau] revert the changes to random forest :(
51f581c [Holden Karau] Add explicit types to public methods, fix long line
f7032eb [Holden Karau] Fix a java test bug, remove some unecessary changes
adf15b4 [Holden Karau] rename the classifier suite test to ProbabilisticClassifierSuite now that we only have it in Probabilistic
398078a [Holden Karau] move the thresholding around a bunch based on the design doc
4893bdc [Holden Karau] Use numtrees of 3 since previous result was tied (one tree for each) and the switch from different max methods picked a different element (since they were equal I think this is ok)
638854c [Holden Karau] Add a scala RandomForestClassifierSuite test based on corresponding python test
e09919c [Holden Karau] Fix return type, I need more coffee....
8d92cac [Holden Karau] Use ClassifierParams as the head
3456ed3 [Holden Karau] Add explicit return types even though just test
a0f3b0c [Holden Karau] scala style fixes
6f14314 [Holden Karau] Since hasthreshold/hasthresholds is in root classifier now
ffc8dab [Holden Karau] Update the sharedParams
0420290 [Holden Karau] Allow us to override the get methods selectively
978e77a [Holden Karau] Move HasThreshold into classifier params and start defining the overloaded getThreshold/getThresholds functions
1433e52 [Holden Karau] Revert "try and hide threshold but chainges the API so no dice there"
1f09a2e [Holden Karau] try and hide threshold but chainges the API so no dice there
efb9084 [Holden Karau] move setThresholds only to where its used
6b34809 [Holden Karau] Add a test with thresholding for the RFCS
74f54c3 [Holden Karau] Fix creation of vote array
1986fa8 [Holden Karau] Setting the thresholds only makes sense if the underlying class hasn't overridden predict, so lets push it down.
2f44b18 [Holden Karau] Add a global default of null for thresholds param
f338cfc [Holden Karau] Wait that wasn't a good idea, Revert "Some progress towards unifying threshold and thresholds"
634b06f [Holden Karau] Some progress towards unifying threshold and thresholds
85c9e01 [Holden Karau] Test passes again... little fnur
099c0f3 [Holden Karau] Move thresholds around some more (set on model not trainer)
0f46836 [Holden Karau] Start adding a classifiersuite
f70eb5e [Holden Karau] Fix test compile issues
a7d59c8 [Holden Karau] Move thresholding into Classifier trait
5d999d2 [Holden Karau] Some more progress, start adding a test (maybe try and see if we can find a better thing to use for the base of the test)
1fed644 [Holden Karau] Use thresholds to scale scores in random forest classifcation
31d6bf2 [Holden Karau] Start threading the threshold info through
0ef228c [Holden Karau] Add hasthresholds
2015-08-04 13:12:22 -04:00
|
|
|
threshold=None, thresholds=None, \
|
|
|
|
probabilityCol="probability", rawPredictionCol="rawPrediction")
|
2015-02-15 23:29:26 -05:00
|
|
|
Sets params for logistic regression.
|
[SPARK-8069] [ML] Add multiclass thresholds for ProbabilisticClassifier
This PR replaces the old "threshold" with a generalized "thresholds" Param. We keep getThreshold,setThreshold for backwards compatibility for binary classification.
Note that the primary author of this PR is holdenk
Author: Holden Karau <holden@pigscanfly.ca>
Author: Joseph K. Bradley <joseph@databricks.com>
Closes #7909 from jkbradley/holdenk-SPARK-8069-add-cutoff-aka-threshold-to-random-forest and squashes the following commits:
3952977 [Joseph K. Bradley] fixed pyspark doc test
85febc8 [Joseph K. Bradley] made python unit tests a little more robust
7eb1d86 [Joseph K. Bradley] small cleanups
6cc2ed8 [Joseph K. Bradley] Fixed remaining merge issues.
0255e44 [Joseph K. Bradley] Many cleanups for thresholds, some more tests
7565a60 [Holden Karau] fix pep8 style checks, add a getThreshold method similar to our LogisticRegression.scala one for API compat
be87f26 [Holden Karau] Convert threshold to thresholds in the python code, add specialized support for Array[Double] to shared parems codegen, etc.
6747dad [Holden Karau] Override raw2prediction for ProbabilisticClassifier, fix some tests
25df168 [Holden Karau] Fix handling of thresholds in LogisticRegression
c02d6c0 [Holden Karau] No default for thresholds
5e43628 [Holden Karau] CR feedback and fixed the renamed test
f3fbbd1 [Holden Karau] revert the changes to random forest :(
51f581c [Holden Karau] Add explicit types to public methods, fix long line
f7032eb [Holden Karau] Fix a java test bug, remove some unecessary changes
adf15b4 [Holden Karau] rename the classifier suite test to ProbabilisticClassifierSuite now that we only have it in Probabilistic
398078a [Holden Karau] move the thresholding around a bunch based on the design doc
4893bdc [Holden Karau] Use numtrees of 3 since previous result was tied (one tree for each) and the switch from different max methods picked a different element (since they were equal I think this is ok)
638854c [Holden Karau] Add a scala RandomForestClassifierSuite test based on corresponding python test
e09919c [Holden Karau] Fix return type, I need more coffee....
8d92cac [Holden Karau] Use ClassifierParams as the head
3456ed3 [Holden Karau] Add explicit return types even though just test
a0f3b0c [Holden Karau] scala style fixes
6f14314 [Holden Karau] Since hasthreshold/hasthresholds is in root classifier now
ffc8dab [Holden Karau] Update the sharedParams
0420290 [Holden Karau] Allow us to override the get methods selectively
978e77a [Holden Karau] Move HasThreshold into classifier params and start defining the overloaded getThreshold/getThresholds functions
1433e52 [Holden Karau] Revert "try and hide threshold but chainges the API so no dice there"
1f09a2e [Holden Karau] try and hide threshold but chainges the API so no dice there
efb9084 [Holden Karau] move setThresholds only to where its used
6b34809 [Holden Karau] Add a test with thresholding for the RFCS
74f54c3 [Holden Karau] Fix creation of vote array
1986fa8 [Holden Karau] Setting the thresholds only makes sense if the underlying class hasn't overridden predict, so lets push it down.
2f44b18 [Holden Karau] Add a global default of null for thresholds param
f338cfc [Holden Karau] Wait that wasn't a good idea, Revert "Some progress towards unifying threshold and thresholds"
634b06f [Holden Karau] Some progress towards unifying threshold and thresholds
85c9e01 [Holden Karau] Test passes again... little fnur
099c0f3 [Holden Karau] Move thresholds around some more (set on model not trainer)
0f46836 [Holden Karau] Start adding a classifiersuite
f70eb5e [Holden Karau] Fix test compile issues
a7d59c8 [Holden Karau] Move thresholding into Classifier trait
5d999d2 [Holden Karau] Some more progress, start adding a test (maybe try and see if we can find a better thing to use for the base of the test)
1fed644 [Holden Karau] Use thresholds to scale scores in random forest classifcation
31d6bf2 [Holden Karau] Start threading the threshold info through
0ef228c [Holden Karau] Add hasthresholds
2015-08-04 13:12:22 -04:00
|
|
|
Param thresholds overrides Param threshold; threshold is provided
|
|
|
|
for backwards compatibility and only applies to binary classification.
|
2015-02-15 23:29:26 -05:00
|
|
|
"""
|
[SPARK-8069] [ML] Add multiclass thresholds for ProbabilisticClassifier
This PR replaces the old "threshold" with a generalized "thresholds" Param. We keep getThreshold,setThreshold for backwards compatibility for binary classification.
Note that the primary author of this PR is holdenk
Author: Holden Karau <holden@pigscanfly.ca>
Author: Joseph K. Bradley <joseph@databricks.com>
Closes #7909 from jkbradley/holdenk-SPARK-8069-add-cutoff-aka-threshold-to-random-forest and squashes the following commits:
3952977 [Joseph K. Bradley] fixed pyspark doc test
85febc8 [Joseph K. Bradley] made python unit tests a little more robust
7eb1d86 [Joseph K. Bradley] small cleanups
6cc2ed8 [Joseph K. Bradley] Fixed remaining merge issues.
0255e44 [Joseph K. Bradley] Many cleanups for thresholds, some more tests
7565a60 [Holden Karau] fix pep8 style checks, add a getThreshold method similar to our LogisticRegression.scala one for API compat
be87f26 [Holden Karau] Convert threshold to thresholds in the python code, add specialized support for Array[Double] to shared parems codegen, etc.
6747dad [Holden Karau] Override raw2prediction for ProbabilisticClassifier, fix some tests
25df168 [Holden Karau] Fix handling of thresholds in LogisticRegression
c02d6c0 [Holden Karau] No default for thresholds
5e43628 [Holden Karau] CR feedback and fixed the renamed test
f3fbbd1 [Holden Karau] revert the changes to random forest :(
51f581c [Holden Karau] Add explicit types to public methods, fix long line
f7032eb [Holden Karau] Fix a java test bug, remove some unecessary changes
adf15b4 [Holden Karau] rename the classifier suite test to ProbabilisticClassifierSuite now that we only have it in Probabilistic
398078a [Holden Karau] move the thresholding around a bunch based on the design doc
4893bdc [Holden Karau] Use numtrees of 3 since previous result was tied (one tree for each) and the switch from different max methods picked a different element (since they were equal I think this is ok)
638854c [Holden Karau] Add a scala RandomForestClassifierSuite test based on corresponding python test
e09919c [Holden Karau] Fix return type, I need more coffee....
8d92cac [Holden Karau] Use ClassifierParams as the head
3456ed3 [Holden Karau] Add explicit return types even though just test
a0f3b0c [Holden Karau] scala style fixes
6f14314 [Holden Karau] Since hasthreshold/hasthresholds is in root classifier now
ffc8dab [Holden Karau] Update the sharedParams
0420290 [Holden Karau] Allow us to override the get methods selectively
978e77a [Holden Karau] Move HasThreshold into classifier params and start defining the overloaded getThreshold/getThresholds functions
1433e52 [Holden Karau] Revert "try and hide threshold but chainges the API so no dice there"
1f09a2e [Holden Karau] try and hide threshold but chainges the API so no dice there
efb9084 [Holden Karau] move setThresholds only to where its used
6b34809 [Holden Karau] Add a test with thresholding for the RFCS
74f54c3 [Holden Karau] Fix creation of vote array
1986fa8 [Holden Karau] Setting the thresholds only makes sense if the underlying class hasn't overridden predict, so lets push it down.
2f44b18 [Holden Karau] Add a global default of null for thresholds param
f338cfc [Holden Karau] Wait that wasn't a good idea, Revert "Some progress towards unifying threshold and thresholds"
634b06f [Holden Karau] Some progress towards unifying threshold and thresholds
85c9e01 [Holden Karau] Test passes again... little fnur
099c0f3 [Holden Karau] Move thresholds around some more (set on model not trainer)
0f46836 [Holden Karau] Start adding a classifiersuite
f70eb5e [Holden Karau] Fix test compile issues
a7d59c8 [Holden Karau] Move thresholding into Classifier trait
5d999d2 [Holden Karau] Some more progress, start adding a test (maybe try and see if we can find a better thing to use for the base of the test)
1fed644 [Holden Karau] Use thresholds to scale scores in random forest classifcation
31d6bf2 [Holden Karau] Start threading the threshold info through
0ef228c [Holden Karau] Add hasthresholds
2015-08-04 13:12:22 -04:00
|
|
|
# Under the hood we use thresholds so translate threshold to thresholds if applicable
|
|
|
|
if thresholds is None and threshold is not None:
|
|
|
|
kwargs[thresholds] = [1-threshold, threshold]
|
2015-02-15 23:29:26 -05:00
|
|
|
kwargs = self.setParams._input_kwargs
|
2015-04-16 02:49:42 -04:00
|
|
|
return self._set(**kwargs)
|
2015-02-15 23:29:26 -05:00
|
|
|
|
2015-01-28 20:14:23 -05:00
|
|
|
def _create_model(self, java_model):
|
|
|
|
return LogisticRegressionModel(java_model)
|
|
|
|
|
2015-05-13 18:13:09 -04:00
|
|
|
def setElasticNetParam(self, value):
|
|
|
|
"""
|
|
|
|
Sets the value of :py:attr:`elasticNetParam`.
|
|
|
|
"""
|
2015-05-18 15:02:18 -04:00
|
|
|
self._paramMap[self.elasticNetParam] = value
|
2015-05-13 18:13:09 -04:00
|
|
|
return self
|
|
|
|
|
|
|
|
def getElasticNetParam(self):
|
|
|
|
"""
|
|
|
|
Gets the value of elasticNetParam or its default value.
|
|
|
|
"""
|
|
|
|
return self.getOrDefault(self.elasticNetParam)
|
|
|
|
|
|
|
|
def setFitIntercept(self, value):
|
|
|
|
"""
|
|
|
|
Sets the value of :py:attr:`fitIntercept`.
|
|
|
|
"""
|
2015-05-18 15:02:18 -04:00
|
|
|
self._paramMap[self.fitIntercept] = value
|
2015-05-13 18:13:09 -04:00
|
|
|
return self
|
|
|
|
|
|
|
|
def getFitIntercept(self):
|
|
|
|
"""
|
|
|
|
Gets the value of fitIntercept or its default value.
|
|
|
|
"""
|
|
|
|
return self.getOrDefault(self.fitIntercept)
|
|
|
|
|
|
|
|
def setThreshold(self, value):
|
|
|
|
"""
|
[SPARK-8069] [ML] Add multiclass thresholds for ProbabilisticClassifier
This PR replaces the old "threshold" with a generalized "thresholds" Param. We keep getThreshold,setThreshold for backwards compatibility for binary classification.
Note that the primary author of this PR is holdenk
Author: Holden Karau <holden@pigscanfly.ca>
Author: Joseph K. Bradley <joseph@databricks.com>
Closes #7909 from jkbradley/holdenk-SPARK-8069-add-cutoff-aka-threshold-to-random-forest and squashes the following commits:
3952977 [Joseph K. Bradley] fixed pyspark doc test
85febc8 [Joseph K. Bradley] made python unit tests a little more robust
7eb1d86 [Joseph K. Bradley] small cleanups
6cc2ed8 [Joseph K. Bradley] Fixed remaining merge issues.
0255e44 [Joseph K. Bradley] Many cleanups for thresholds, some more tests
7565a60 [Holden Karau] fix pep8 style checks, add a getThreshold method similar to our LogisticRegression.scala one for API compat
be87f26 [Holden Karau] Convert threshold to thresholds in the python code, add specialized support for Array[Double] to shared parems codegen, etc.
6747dad [Holden Karau] Override raw2prediction for ProbabilisticClassifier, fix some tests
25df168 [Holden Karau] Fix handling of thresholds in LogisticRegression
c02d6c0 [Holden Karau] No default for thresholds
5e43628 [Holden Karau] CR feedback and fixed the renamed test
f3fbbd1 [Holden Karau] revert the changes to random forest :(
51f581c [Holden Karau] Add explicit types to public methods, fix long line
f7032eb [Holden Karau] Fix a java test bug, remove some unecessary changes
adf15b4 [Holden Karau] rename the classifier suite test to ProbabilisticClassifierSuite now that we only have it in Probabilistic
398078a [Holden Karau] move the thresholding around a bunch based on the design doc
4893bdc [Holden Karau] Use numtrees of 3 since previous result was tied (one tree for each) and the switch from different max methods picked a different element (since they were equal I think this is ok)
638854c [Holden Karau] Add a scala RandomForestClassifierSuite test based on corresponding python test
e09919c [Holden Karau] Fix return type, I need more coffee....
8d92cac [Holden Karau] Use ClassifierParams as the head
3456ed3 [Holden Karau] Add explicit return types even though just test
a0f3b0c [Holden Karau] scala style fixes
6f14314 [Holden Karau] Since hasthreshold/hasthresholds is in root classifier now
ffc8dab [Holden Karau] Update the sharedParams
0420290 [Holden Karau] Allow us to override the get methods selectively
978e77a [Holden Karau] Move HasThreshold into classifier params and start defining the overloaded getThreshold/getThresholds functions
1433e52 [Holden Karau] Revert "try and hide threshold but chainges the API so no dice there"
1f09a2e [Holden Karau] try and hide threshold but chainges the API so no dice there
efb9084 [Holden Karau] move setThresholds only to where its used
6b34809 [Holden Karau] Add a test with thresholding for the RFCS
74f54c3 [Holden Karau] Fix creation of vote array
1986fa8 [Holden Karau] Setting the thresholds only makes sense if the underlying class hasn't overridden predict, so lets push it down.
2f44b18 [Holden Karau] Add a global default of null for thresholds param
f338cfc [Holden Karau] Wait that wasn't a good idea, Revert "Some progress towards unifying threshold and thresholds"
634b06f [Holden Karau] Some progress towards unifying threshold and thresholds
85c9e01 [Holden Karau] Test passes again... little fnur
099c0f3 [Holden Karau] Move thresholds around some more (set on model not trainer)
0f46836 [Holden Karau] Start adding a classifiersuite
f70eb5e [Holden Karau] Fix test compile issues
a7d59c8 [Holden Karau] Move thresholding into Classifier trait
5d999d2 [Holden Karau] Some more progress, start adding a test (maybe try and see if we can find a better thing to use for the base of the test)
1fed644 [Holden Karau] Use thresholds to scale scores in random forest classifcation
31d6bf2 [Holden Karau] Start threading the threshold info through
0ef228c [Holden Karau] Add hasthresholds
2015-08-04 13:12:22 -04:00
|
|
|
Sets the value of :py:attr:`thresholds` using [1-value, value].
|
|
|
|
|
|
|
|
>>> lr = LogisticRegression()
|
|
|
|
>>> lr.getThreshold()
|
|
|
|
0.5
|
|
|
|
>>> lr.setThreshold(0.6)
|
|
|
|
LogisticRegression_...
|
|
|
|
>>> abs(lr.getThreshold() - 0.6) < 1e-5
|
|
|
|
True
|
|
|
|
"""
|
|
|
|
return self.setThresholds([1-value, value])
|
|
|
|
|
|
|
|
def setThresholds(self, value):
|
|
|
|
"""
|
|
|
|
Sets the value of :py:attr:`thresholds`.
|
2015-05-13 18:13:09 -04:00
|
|
|
"""
|
[SPARK-8069] [ML] Add multiclass thresholds for ProbabilisticClassifier
This PR replaces the old "threshold" with a generalized "thresholds" Param. We keep getThreshold,setThreshold for backwards compatibility for binary classification.
Note that the primary author of this PR is holdenk
Author: Holden Karau <holden@pigscanfly.ca>
Author: Joseph K. Bradley <joseph@databricks.com>
Closes #7909 from jkbradley/holdenk-SPARK-8069-add-cutoff-aka-threshold-to-random-forest and squashes the following commits:
3952977 [Joseph K. Bradley] fixed pyspark doc test
85febc8 [Joseph K. Bradley] made python unit tests a little more robust
7eb1d86 [Joseph K. Bradley] small cleanups
6cc2ed8 [Joseph K. Bradley] Fixed remaining merge issues.
0255e44 [Joseph K. Bradley] Many cleanups for thresholds, some more tests
7565a60 [Holden Karau] fix pep8 style checks, add a getThreshold method similar to our LogisticRegression.scala one for API compat
be87f26 [Holden Karau] Convert threshold to thresholds in the python code, add specialized support for Array[Double] to shared parems codegen, etc.
6747dad [Holden Karau] Override raw2prediction for ProbabilisticClassifier, fix some tests
25df168 [Holden Karau] Fix handling of thresholds in LogisticRegression
c02d6c0 [Holden Karau] No default for thresholds
5e43628 [Holden Karau] CR feedback and fixed the renamed test
f3fbbd1 [Holden Karau] revert the changes to random forest :(
51f581c [Holden Karau] Add explicit types to public methods, fix long line
f7032eb [Holden Karau] Fix a java test bug, remove some unecessary changes
adf15b4 [Holden Karau] rename the classifier suite test to ProbabilisticClassifierSuite now that we only have it in Probabilistic
398078a [Holden Karau] move the thresholding around a bunch based on the design doc
4893bdc [Holden Karau] Use numtrees of 3 since previous result was tied (one tree for each) and the switch from different max methods picked a different element (since they were equal I think this is ok)
638854c [Holden Karau] Add a scala RandomForestClassifierSuite test based on corresponding python test
e09919c [Holden Karau] Fix return type, I need more coffee....
8d92cac [Holden Karau] Use ClassifierParams as the head
3456ed3 [Holden Karau] Add explicit return types even though just test
a0f3b0c [Holden Karau] scala style fixes
6f14314 [Holden Karau] Since hasthreshold/hasthresholds is in root classifier now
ffc8dab [Holden Karau] Update the sharedParams
0420290 [Holden Karau] Allow us to override the get methods selectively
978e77a [Holden Karau] Move HasThreshold into classifier params and start defining the overloaded getThreshold/getThresholds functions
1433e52 [Holden Karau] Revert "try and hide threshold but chainges the API so no dice there"
1f09a2e [Holden Karau] try and hide threshold but chainges the API so no dice there
efb9084 [Holden Karau] move setThresholds only to where its used
6b34809 [Holden Karau] Add a test with thresholding for the RFCS
74f54c3 [Holden Karau] Fix creation of vote array
1986fa8 [Holden Karau] Setting the thresholds only makes sense if the underlying class hasn't overridden predict, so lets push it down.
2f44b18 [Holden Karau] Add a global default of null for thresholds param
f338cfc [Holden Karau] Wait that wasn't a good idea, Revert "Some progress towards unifying threshold and thresholds"
634b06f [Holden Karau] Some progress towards unifying threshold and thresholds
85c9e01 [Holden Karau] Test passes again... little fnur
099c0f3 [Holden Karau] Move thresholds around some more (set on model not trainer)
0f46836 [Holden Karau] Start adding a classifiersuite
f70eb5e [Holden Karau] Fix test compile issues
a7d59c8 [Holden Karau] Move thresholding into Classifier trait
5d999d2 [Holden Karau] Some more progress, start adding a test (maybe try and see if we can find a better thing to use for the base of the test)
1fed644 [Holden Karau] Use thresholds to scale scores in random forest classifcation
31d6bf2 [Holden Karau] Start threading the threshold info through
0ef228c [Holden Karau] Add hasthresholds
2015-08-04 13:12:22 -04:00
|
|
|
self._paramMap[self.thresholds] = value
|
2015-05-13 18:13:09 -04:00
|
|
|
return self
|
|
|
|
|
[SPARK-8069] [ML] Add multiclass thresholds for ProbabilisticClassifier
This PR replaces the old "threshold" with a generalized "thresholds" Param. We keep getThreshold,setThreshold for backwards compatibility for binary classification.
Note that the primary author of this PR is holdenk
Author: Holden Karau <holden@pigscanfly.ca>
Author: Joseph K. Bradley <joseph@databricks.com>
Closes #7909 from jkbradley/holdenk-SPARK-8069-add-cutoff-aka-threshold-to-random-forest and squashes the following commits:
3952977 [Joseph K. Bradley] fixed pyspark doc test
85febc8 [Joseph K. Bradley] made python unit tests a little more robust
7eb1d86 [Joseph K. Bradley] small cleanups
6cc2ed8 [Joseph K. Bradley] Fixed remaining merge issues.
0255e44 [Joseph K. Bradley] Many cleanups for thresholds, some more tests
7565a60 [Holden Karau] fix pep8 style checks, add a getThreshold method similar to our LogisticRegression.scala one for API compat
be87f26 [Holden Karau] Convert threshold to thresholds in the python code, add specialized support for Array[Double] to shared parems codegen, etc.
6747dad [Holden Karau] Override raw2prediction for ProbabilisticClassifier, fix some tests
25df168 [Holden Karau] Fix handling of thresholds in LogisticRegression
c02d6c0 [Holden Karau] No default for thresholds
5e43628 [Holden Karau] CR feedback and fixed the renamed test
f3fbbd1 [Holden Karau] revert the changes to random forest :(
51f581c [Holden Karau] Add explicit types to public methods, fix long line
f7032eb [Holden Karau] Fix a java test bug, remove some unecessary changes
adf15b4 [Holden Karau] rename the classifier suite test to ProbabilisticClassifierSuite now that we only have it in Probabilistic
398078a [Holden Karau] move the thresholding around a bunch based on the design doc
4893bdc [Holden Karau] Use numtrees of 3 since previous result was tied (one tree for each) and the switch from different max methods picked a different element (since they were equal I think this is ok)
638854c [Holden Karau] Add a scala RandomForestClassifierSuite test based on corresponding python test
e09919c [Holden Karau] Fix return type, I need more coffee....
8d92cac [Holden Karau] Use ClassifierParams as the head
3456ed3 [Holden Karau] Add explicit return types even though just test
a0f3b0c [Holden Karau] scala style fixes
6f14314 [Holden Karau] Since hasthreshold/hasthresholds is in root classifier now
ffc8dab [Holden Karau] Update the sharedParams
0420290 [Holden Karau] Allow us to override the get methods selectively
978e77a [Holden Karau] Move HasThreshold into classifier params and start defining the overloaded getThreshold/getThresholds functions
1433e52 [Holden Karau] Revert "try and hide threshold but chainges the API so no dice there"
1f09a2e [Holden Karau] try and hide threshold but chainges the API so no dice there
efb9084 [Holden Karau] move setThresholds only to where its used
6b34809 [Holden Karau] Add a test with thresholding for the RFCS
74f54c3 [Holden Karau] Fix creation of vote array
1986fa8 [Holden Karau] Setting the thresholds only makes sense if the underlying class hasn't overridden predict, so lets push it down.
2f44b18 [Holden Karau] Add a global default of null for thresholds param
f338cfc [Holden Karau] Wait that wasn't a good idea, Revert "Some progress towards unifying threshold and thresholds"
634b06f [Holden Karau] Some progress towards unifying threshold and thresholds
85c9e01 [Holden Karau] Test passes again... little fnur
099c0f3 [Holden Karau] Move thresholds around some more (set on model not trainer)
0f46836 [Holden Karau] Start adding a classifiersuite
f70eb5e [Holden Karau] Fix test compile issues
a7d59c8 [Holden Karau] Move thresholding into Classifier trait
5d999d2 [Holden Karau] Some more progress, start adding a test (maybe try and see if we can find a better thing to use for the base of the test)
1fed644 [Holden Karau] Use thresholds to scale scores in random forest classifcation
31d6bf2 [Holden Karau] Start threading the threshold info through
0ef228c [Holden Karau] Add hasthresholds
2015-08-04 13:12:22 -04:00
|
|
|
def getThresholds(self):
|
|
|
|
"""
|
|
|
|
Gets the value of thresholds or its default value.
|
|
|
|
"""
|
|
|
|
return self.getOrDefault(self.thresholds)
|
|
|
|
|
2015-05-13 18:13:09 -04:00
|
|
|
def getThreshold(self):
|
|
|
|
"""
|
|
|
|
Gets the value of threshold or its default value.
|
|
|
|
"""
|
[SPARK-8069] [ML] Add multiclass thresholds for ProbabilisticClassifier
This PR replaces the old "threshold" with a generalized "thresholds" Param. We keep getThreshold,setThreshold for backwards compatibility for binary classification.
Note that the primary author of this PR is holdenk
Author: Holden Karau <holden@pigscanfly.ca>
Author: Joseph K. Bradley <joseph@databricks.com>
Closes #7909 from jkbradley/holdenk-SPARK-8069-add-cutoff-aka-threshold-to-random-forest and squashes the following commits:
3952977 [Joseph K. Bradley] fixed pyspark doc test
85febc8 [Joseph K. Bradley] made python unit tests a little more robust
7eb1d86 [Joseph K. Bradley] small cleanups
6cc2ed8 [Joseph K. Bradley] Fixed remaining merge issues.
0255e44 [Joseph K. Bradley] Many cleanups for thresholds, some more tests
7565a60 [Holden Karau] fix pep8 style checks, add a getThreshold method similar to our LogisticRegression.scala one for API compat
be87f26 [Holden Karau] Convert threshold to thresholds in the python code, add specialized support for Array[Double] to shared parems codegen, etc.
6747dad [Holden Karau] Override raw2prediction for ProbabilisticClassifier, fix some tests
25df168 [Holden Karau] Fix handling of thresholds in LogisticRegression
c02d6c0 [Holden Karau] No default for thresholds
5e43628 [Holden Karau] CR feedback and fixed the renamed test
f3fbbd1 [Holden Karau] revert the changes to random forest :(
51f581c [Holden Karau] Add explicit types to public methods, fix long line
f7032eb [Holden Karau] Fix a java test bug, remove some unecessary changes
adf15b4 [Holden Karau] rename the classifier suite test to ProbabilisticClassifierSuite now that we only have it in Probabilistic
398078a [Holden Karau] move the thresholding around a bunch based on the design doc
4893bdc [Holden Karau] Use numtrees of 3 since previous result was tied (one tree for each) and the switch from different max methods picked a different element (since they were equal I think this is ok)
638854c [Holden Karau] Add a scala RandomForestClassifierSuite test based on corresponding python test
e09919c [Holden Karau] Fix return type, I need more coffee....
8d92cac [Holden Karau] Use ClassifierParams as the head
3456ed3 [Holden Karau] Add explicit return types even though just test
a0f3b0c [Holden Karau] scala style fixes
6f14314 [Holden Karau] Since hasthreshold/hasthresholds is in root classifier now
ffc8dab [Holden Karau] Update the sharedParams
0420290 [Holden Karau] Allow us to override the get methods selectively
978e77a [Holden Karau] Move HasThreshold into classifier params and start defining the overloaded getThreshold/getThresholds functions
1433e52 [Holden Karau] Revert "try and hide threshold but chainges the API so no dice there"
1f09a2e [Holden Karau] try and hide threshold but chainges the API so no dice there
efb9084 [Holden Karau] move setThresholds only to where its used
6b34809 [Holden Karau] Add a test with thresholding for the RFCS
74f54c3 [Holden Karau] Fix creation of vote array
1986fa8 [Holden Karau] Setting the thresholds only makes sense if the underlying class hasn't overridden predict, so lets push it down.
2f44b18 [Holden Karau] Add a global default of null for thresholds param
f338cfc [Holden Karau] Wait that wasn't a good idea, Revert "Some progress towards unifying threshold and thresholds"
634b06f [Holden Karau] Some progress towards unifying threshold and thresholds
85c9e01 [Holden Karau] Test passes again... little fnur
099c0f3 [Holden Karau] Move thresholds around some more (set on model not trainer)
0f46836 [Holden Karau] Start adding a classifiersuite
f70eb5e [Holden Karau] Fix test compile issues
a7d59c8 [Holden Karau] Move thresholding into Classifier trait
5d999d2 [Holden Karau] Some more progress, start adding a test (maybe try and see if we can find a better thing to use for the base of the test)
1fed644 [Holden Karau] Use thresholds to scale scores in random forest classifcation
31d6bf2 [Holden Karau] Start threading the threshold info through
0ef228c [Holden Karau] Add hasthresholds
2015-08-04 13:12:22 -04:00
|
|
|
if self.isDefined(self.thresholds):
|
|
|
|
thresholds = self.getOrDefault(self.thresholds)
|
|
|
|
if len(thresholds) != 2:
|
|
|
|
raise ValueError("Logistic Regression getThreshold only applies to" +
|
|
|
|
" binary classification, but thresholds has length != 2." +
|
|
|
|
" thresholds: " + ",".join(thresholds))
|
|
|
|
return 1.0/(1.0+thresholds[0]/thresholds[1])
|
|
|
|
else:
|
|
|
|
return 0.5
|
2015-05-13 18:13:09 -04:00
|
|
|
|
2015-01-28 20:14:23 -05:00
|
|
|
|
|
|
|
class LogisticRegressionModel(JavaModel):
|
|
|
|
"""
|
|
|
|
Model fitted by LogisticRegression.
|
|
|
|
"""
|
|
|
|
|
2015-05-14 21:13:58 -04:00
|
|
|
@property
|
|
|
|
def weights(self):
|
|
|
|
"""
|
|
|
|
Model weights.
|
|
|
|
"""
|
|
|
|
return self._call_java("weights")
|
|
|
|
|
|
|
|
@property
|
|
|
|
def intercept(self):
|
|
|
|
"""
|
|
|
|
Model intercept.
|
|
|
|
"""
|
|
|
|
return self._call_java("intercept")
|
|
|
|
|
2015-01-28 20:14:23 -05:00
|
|
|
|
2015-05-13 18:13:09 -04:00
|
|
|
class TreeClassifierParams(object):
|
|
|
|
"""
|
|
|
|
Private class to track supported impurity measures.
|
|
|
|
"""
|
|
|
|
supportedImpurities = ["entropy", "gini"]
|
|
|
|
|
|
|
|
|
|
|
|
class GBTParams(object):
|
|
|
|
"""
|
|
|
|
Private class to track supported GBT params.
|
|
|
|
"""
|
|
|
|
supportedLossTypes = ["logistic"]
|
|
|
|
|
|
|
|
|
|
|
|
@inherit_doc
|
|
|
|
class DecisionTreeClassifier(JavaEstimator, HasFeaturesCol, HasLabelCol, HasPredictionCol,
|
2015-08-03 01:19:27 -04:00
|
|
|
HasProbabilityCol, HasRawPredictionCol, DecisionTreeParams,
|
|
|
|
HasCheckpointInterval):
|
2015-05-13 18:13:09 -04:00
|
|
|
"""
|
|
|
|
`http://en.wikipedia.org/wiki/Decision_tree_learning Decision tree`
|
|
|
|
learning algorithm for classification.
|
|
|
|
It supports both binary and multiclass labels, as well as both continuous and categorical
|
|
|
|
features.
|
|
|
|
|
|
|
|
>>> from pyspark.mllib.linalg import Vectors
|
|
|
|
>>> from pyspark.ml.feature import StringIndexer
|
|
|
|
>>> df = sqlContext.createDataFrame([
|
|
|
|
... (1.0, Vectors.dense(1.0)),
|
|
|
|
... (0.0, Vectors.sparse(1, [], []))], ["label", "features"])
|
|
|
|
>>> stringIndexer = StringIndexer(inputCol="label", outputCol="indexed")
|
|
|
|
>>> si_model = stringIndexer.fit(df)
|
|
|
|
>>> td = si_model.transform(df)
|
|
|
|
>>> dt = DecisionTreeClassifier(maxDepth=2, labelCol="indexed")
|
|
|
|
>>> model = dt.fit(td)
|
2015-07-07 11:58:08 -04:00
|
|
|
>>> model.numNodes
|
|
|
|
3
|
|
|
|
>>> model.depth
|
|
|
|
1
|
2015-05-13 18:13:09 -04:00
|
|
|
>>> test0 = sqlContext.createDataFrame([(Vectors.dense(-1.0),)], ["features"])
|
2015-08-03 01:19:27 -04:00
|
|
|
>>> result = model.transform(test0).head()
|
|
|
|
>>> result.prediction
|
2015-05-13 18:13:09 -04:00
|
|
|
0.0
|
2015-08-03 01:19:27 -04:00
|
|
|
>>> result.probability
|
|
|
|
DenseVector([1.0, 0.0])
|
|
|
|
>>> result.rawPrediction
|
|
|
|
DenseVector([1.0, 0.0])
|
2015-05-13 18:13:09 -04:00
|
|
|
>>> test1 = sqlContext.createDataFrame([(Vectors.sparse(1, [0], [1.0]),)], ["features"])
|
|
|
|
>>> model.transform(test1).head().prediction
|
|
|
|
1.0
|
|
|
|
"""
|
|
|
|
|
|
|
|
# a placeholder to make it appear in the generated doc
|
|
|
|
impurity = Param(Params._dummy(), "impurity",
|
|
|
|
"Criterion used for information gain calculation (case-insensitive). " +
|
|
|
|
"Supported options: " + ", ".join(TreeClassifierParams.supportedImpurities))
|
|
|
|
|
|
|
|
@keyword_only
|
|
|
|
def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction",
|
2015-08-03 01:19:27 -04:00
|
|
|
probabilityCol="probability", rawPredictionCol="rawPrediction",
|
2015-05-13 18:13:09 -04:00
|
|
|
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
|
|
|
|
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity="gini"):
|
|
|
|
"""
|
|
|
|
__init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
|
2015-08-03 01:19:27 -04:00
|
|
|
probabilityCol="probability", rawPredictionCol="rawPrediction", \
|
2015-05-14 21:16:22 -04:00
|
|
|
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \
|
2015-05-13 18:13:09 -04:00
|
|
|
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity="gini")
|
|
|
|
"""
|
|
|
|
super(DecisionTreeClassifier, self).__init__()
|
2015-05-18 15:02:18 -04:00
|
|
|
self._java_obj = self._new_java_obj(
|
|
|
|
"org.apache.spark.ml.classification.DecisionTreeClassifier", self.uid)
|
2015-05-13 18:13:09 -04:00
|
|
|
#: param for Criterion used for information gain calculation (case-insensitive).
|
|
|
|
self.impurity = \
|
|
|
|
Param(self, "impurity",
|
|
|
|
"Criterion used for information gain calculation (case-insensitive). " +
|
|
|
|
"Supported options: " + ", ".join(TreeClassifierParams.supportedImpurities))
|
|
|
|
self._setDefault(maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
|
|
|
|
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10,
|
|
|
|
impurity="gini")
|
|
|
|
kwargs = self.__init__._input_kwargs
|
|
|
|
self.setParams(**kwargs)
|
|
|
|
|
|
|
|
@keyword_only
|
|
|
|
def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction",
|
2015-08-03 01:19:27 -04:00
|
|
|
probabilityCol="probability", rawPredictionCol="rawPrediction",
|
2015-05-13 18:13:09 -04:00
|
|
|
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
|
|
|
|
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10,
|
|
|
|
impurity="gini"):
|
|
|
|
"""
|
|
|
|
setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
|
2015-08-03 01:19:27 -04:00
|
|
|
probabilityCol="probability", rawPredictionCol="rawPrediction", \
|
2015-05-14 21:16:22 -04:00
|
|
|
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \
|
|
|
|
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity="gini")
|
2015-05-13 18:13:09 -04:00
|
|
|
Sets params for the DecisionTreeClassifier.
|
|
|
|
"""
|
|
|
|
kwargs = self.setParams._input_kwargs
|
|
|
|
return self._set(**kwargs)
|
|
|
|
|
|
|
|
def _create_model(self, java_model):
|
|
|
|
return DecisionTreeClassificationModel(java_model)
|
|
|
|
|
|
|
|
def setImpurity(self, value):
|
|
|
|
"""
|
|
|
|
Sets the value of :py:attr:`impurity`.
|
|
|
|
"""
|
2015-05-18 15:02:18 -04:00
|
|
|
self._paramMap[self.impurity] = value
|
2015-05-13 18:13:09 -04:00
|
|
|
return self
|
|
|
|
|
|
|
|
def getImpurity(self):
|
|
|
|
"""
|
|
|
|
Gets the value of impurity or its default value.
|
|
|
|
"""
|
|
|
|
return self.getOrDefault(self.impurity)
|
|
|
|
|
|
|
|
|
2015-07-07 11:58:08 -04:00
|
|
|
@inherit_doc
|
|
|
|
class DecisionTreeClassificationModel(DecisionTreeModel):
|
2015-05-13 18:13:09 -04:00
|
|
|
"""
|
|
|
|
Model fitted by DecisionTreeClassifier.
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
@inherit_doc
|
|
|
|
class RandomForestClassifier(JavaEstimator, HasFeaturesCol, HasLabelCol, HasPredictionCol, HasSeed,
|
2015-08-04 17:54:26 -04:00
|
|
|
HasRawPredictionCol, HasProbabilityCol,
|
2015-05-13 18:13:09 -04:00
|
|
|
DecisionTreeParams, HasCheckpointInterval):
|
|
|
|
"""
|
|
|
|
`http://en.wikipedia.org/wiki/Random_forest Random Forest`
|
|
|
|
learning algorithm for classification.
|
|
|
|
It supports both binary and multiclass labels, as well as both continuous and categorical
|
|
|
|
features.
|
|
|
|
|
2015-08-04 17:54:26 -04:00
|
|
|
>>> import numpy
|
2015-07-07 11:58:08 -04:00
|
|
|
>>> from numpy import allclose
|
2015-05-13 18:13:09 -04:00
|
|
|
>>> from pyspark.mllib.linalg import Vectors
|
|
|
|
>>> from pyspark.ml.feature import StringIndexer
|
|
|
|
>>> df = sqlContext.createDataFrame([
|
|
|
|
... (1.0, Vectors.dense(1.0)),
|
|
|
|
... (0.0, Vectors.sparse(1, [], []))], ["label", "features"])
|
|
|
|
>>> stringIndexer = StringIndexer(inputCol="label", outputCol="indexed")
|
|
|
|
>>> si_model = stringIndexer.fit(df)
|
|
|
|
>>> td = si_model.transform(df)
|
2015-07-29 21:18:29 -04:00
|
|
|
>>> rf = RandomForestClassifier(numTrees=3, maxDepth=2, labelCol="indexed", seed=42)
|
2015-05-13 18:13:09 -04:00
|
|
|
>>> model = rf.fit(td)
|
2015-07-29 21:18:29 -04:00
|
|
|
>>> allclose(model.treeWeights, [1.0, 1.0, 1.0])
|
2015-07-07 11:58:08 -04:00
|
|
|
True
|
2015-05-13 18:13:09 -04:00
|
|
|
>>> test0 = sqlContext.createDataFrame([(Vectors.dense(-1.0),)], ["features"])
|
2015-08-04 17:54:26 -04:00
|
|
|
>>> result = model.transform(test0).head()
|
|
|
|
>>> result.prediction
|
2015-05-13 18:13:09 -04:00
|
|
|
0.0
|
2015-08-04 17:54:26 -04:00
|
|
|
>>> numpy.argmax(result.probability)
|
|
|
|
0
|
|
|
|
>>> numpy.argmax(result.rawPrediction)
|
|
|
|
0
|
2015-05-13 18:13:09 -04:00
|
|
|
>>> test1 = sqlContext.createDataFrame([(Vectors.sparse(1, [0], [1.0]),)], ["features"])
|
|
|
|
>>> model.transform(test1).head().prediction
|
|
|
|
1.0
|
|
|
|
"""
|
|
|
|
|
|
|
|
# a placeholder to make it appear in the generated doc
|
|
|
|
impurity = Param(Params._dummy(), "impurity",
|
|
|
|
"Criterion used for information gain calculation (case-insensitive). " +
|
|
|
|
"Supported options: " + ", ".join(TreeClassifierParams.supportedImpurities))
|
|
|
|
subsamplingRate = Param(Params._dummy(), "subsamplingRate",
|
|
|
|
"Fraction of the training data used for learning each decision tree, " +
|
|
|
|
"in range (0, 1].")
|
|
|
|
numTrees = Param(Params._dummy(), "numTrees", "Number of trees to train (>= 1)")
|
|
|
|
featureSubsetStrategy = \
|
|
|
|
Param(Params._dummy(), "featureSubsetStrategy",
|
|
|
|
"The number of features to consider for splits at each tree node. Supported " +
|
|
|
|
"options: " + ", ".join(RandomForestParams.supportedFeatureSubsetStrategies))
|
|
|
|
|
|
|
|
@keyword_only
|
|
|
|
def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction",
|
2015-08-04 17:54:26 -04:00
|
|
|
probabilityCol="probability", rawPredictionCol="rawPrediction",
|
2015-05-13 18:13:09 -04:00
|
|
|
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
|
|
|
|
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity="gini",
|
2015-05-20 18:16:12 -04:00
|
|
|
numTrees=20, featureSubsetStrategy="auto", seed=None):
|
2015-05-13 18:13:09 -04:00
|
|
|
"""
|
2015-05-14 21:16:22 -04:00
|
|
|
__init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
|
2015-08-04 17:54:26 -04:00
|
|
|
probabilityCol="probability", rawPredictionCol="rawPrediction", \
|
2015-05-14 21:16:22 -04:00
|
|
|
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \
|
|
|
|
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity="gini", \
|
2015-05-20 18:16:12 -04:00
|
|
|
numTrees=20, featureSubsetStrategy="auto", seed=None)
|
2015-05-13 18:13:09 -04:00
|
|
|
"""
|
|
|
|
super(RandomForestClassifier, self).__init__()
|
2015-05-18 15:02:18 -04:00
|
|
|
self._java_obj = self._new_java_obj(
|
|
|
|
"org.apache.spark.ml.classification.RandomForestClassifier", self.uid)
|
2015-05-13 18:13:09 -04:00
|
|
|
#: param for Criterion used for information gain calculation (case-insensitive).
|
|
|
|
self.impurity = \
|
|
|
|
Param(self, "impurity",
|
|
|
|
"Criterion used for information gain calculation (case-insensitive). " +
|
|
|
|
"Supported options: " + ", ".join(TreeClassifierParams.supportedImpurities))
|
|
|
|
#: param for Fraction of the training data used for learning each decision tree,
|
|
|
|
# in range (0, 1]
|
|
|
|
self.subsamplingRate = Param(self, "subsamplingRate",
|
|
|
|
"Fraction of the training data used for learning each " +
|
|
|
|
"decision tree, in range (0, 1].")
|
|
|
|
#: param for Number of trees to train (>= 1)
|
|
|
|
self.numTrees = Param(self, "numTrees", "Number of trees to train (>= 1)")
|
|
|
|
#: param for The number of features to consider for splits at each tree node
|
|
|
|
self.featureSubsetStrategy = \
|
|
|
|
Param(self, "featureSubsetStrategy",
|
|
|
|
"The number of features to consider for splits at each tree node. Supported " +
|
|
|
|
"options: " + ", ".join(RandomForestParams.supportedFeatureSubsetStrategies))
|
|
|
|
self._setDefault(maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
|
2015-05-20 18:16:12 -04:00
|
|
|
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, seed=None,
|
2015-05-13 18:13:09 -04:00
|
|
|
impurity="gini", numTrees=20, featureSubsetStrategy="auto")
|
|
|
|
kwargs = self.__init__._input_kwargs
|
|
|
|
self.setParams(**kwargs)
|
|
|
|
|
|
|
|
@keyword_only
|
|
|
|
def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction",
|
2015-08-04 17:54:26 -04:00
|
|
|
probabilityCol="probability", rawPredictionCol="rawPrediction",
|
2015-05-13 18:13:09 -04:00
|
|
|
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
|
2015-05-20 18:16:12 -04:00
|
|
|
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, seed=None,
|
2015-05-13 18:13:09 -04:00
|
|
|
impurity="gini", numTrees=20, featureSubsetStrategy="auto"):
|
|
|
|
"""
|
2015-05-14 21:16:22 -04:00
|
|
|
setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
|
2015-08-04 17:54:26 -04:00
|
|
|
probabilityCol="probability", rawPredictionCol="rawPrediction", \
|
2015-05-14 21:16:22 -04:00
|
|
|
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \
|
2015-05-20 18:16:12 -04:00
|
|
|
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, seed=None, \
|
2015-05-13 18:13:09 -04:00
|
|
|
impurity="gini", numTrees=20, featureSubsetStrategy="auto")
|
|
|
|
Sets params for linear classification.
|
|
|
|
"""
|
|
|
|
kwargs = self.setParams._input_kwargs
|
|
|
|
return self._set(**kwargs)
|
|
|
|
|
|
|
|
def _create_model(self, java_model):
|
|
|
|
return RandomForestClassificationModel(java_model)
|
|
|
|
|
|
|
|
def setImpurity(self, value):
|
|
|
|
"""
|
|
|
|
Sets the value of :py:attr:`impurity`.
|
|
|
|
"""
|
2015-05-18 15:02:18 -04:00
|
|
|
self._paramMap[self.impurity] = value
|
2015-05-13 18:13:09 -04:00
|
|
|
return self
|
|
|
|
|
|
|
|
def getImpurity(self):
|
|
|
|
"""
|
|
|
|
Gets the value of impurity or its default value.
|
|
|
|
"""
|
|
|
|
return self.getOrDefault(self.impurity)
|
|
|
|
|
|
|
|
def setSubsamplingRate(self, value):
|
|
|
|
"""
|
|
|
|
Sets the value of :py:attr:`subsamplingRate`.
|
|
|
|
"""
|
2015-05-18 15:02:18 -04:00
|
|
|
self._paramMap[self.subsamplingRate] = value
|
2015-05-13 18:13:09 -04:00
|
|
|
return self
|
|
|
|
|
|
|
|
def getSubsamplingRate(self):
|
|
|
|
"""
|
|
|
|
Gets the value of subsamplingRate or its default value.
|
|
|
|
"""
|
|
|
|
return self.getOrDefault(self.subsamplingRate)
|
|
|
|
|
|
|
|
def setNumTrees(self, value):
|
|
|
|
"""
|
|
|
|
Sets the value of :py:attr:`numTrees`.
|
|
|
|
"""
|
2015-05-18 15:02:18 -04:00
|
|
|
self._paramMap[self.numTrees] = value
|
2015-05-13 18:13:09 -04:00
|
|
|
return self
|
|
|
|
|
|
|
|
def getNumTrees(self):
|
|
|
|
"""
|
|
|
|
Gets the value of numTrees or its default value.
|
|
|
|
"""
|
|
|
|
return self.getOrDefault(self.numTrees)
|
|
|
|
|
|
|
|
def setFeatureSubsetStrategy(self, value):
|
|
|
|
"""
|
|
|
|
Sets the value of :py:attr:`featureSubsetStrategy`.
|
|
|
|
"""
|
2015-05-18 15:02:18 -04:00
|
|
|
self._paramMap[self.featureSubsetStrategy] = value
|
2015-05-13 18:13:09 -04:00
|
|
|
return self
|
|
|
|
|
|
|
|
def getFeatureSubsetStrategy(self):
|
|
|
|
"""
|
|
|
|
Gets the value of featureSubsetStrategy or its default value.
|
|
|
|
"""
|
|
|
|
return self.getOrDefault(self.featureSubsetStrategy)
|
|
|
|
|
|
|
|
|
2015-07-07 11:58:08 -04:00
|
|
|
class RandomForestClassificationModel(TreeEnsembleModels):
|
2015-05-13 18:13:09 -04:00
|
|
|
"""
|
|
|
|
Model fitted by RandomForestClassifier.
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
@inherit_doc
|
|
|
|
class GBTClassifier(JavaEstimator, HasFeaturesCol, HasLabelCol, HasPredictionCol, HasMaxIter,
|
|
|
|
DecisionTreeParams, HasCheckpointInterval):
|
|
|
|
"""
|
|
|
|
`http://en.wikipedia.org/wiki/Gradient_boosting Gradient-Boosted Trees (GBTs)`
|
|
|
|
learning algorithm for classification.
|
|
|
|
It supports binary labels, as well as both continuous and categorical features.
|
|
|
|
Note: Multiclass labels are not currently supported.
|
|
|
|
|
2015-07-07 11:58:08 -04:00
|
|
|
>>> from numpy import allclose
|
2015-05-13 18:13:09 -04:00
|
|
|
>>> from pyspark.mllib.linalg import Vectors
|
|
|
|
>>> from pyspark.ml.feature import StringIndexer
|
|
|
|
>>> df = sqlContext.createDataFrame([
|
|
|
|
... (1.0, Vectors.dense(1.0)),
|
|
|
|
... (0.0, Vectors.sparse(1, [], []))], ["label", "features"])
|
|
|
|
>>> stringIndexer = StringIndexer(inputCol="label", outputCol="indexed")
|
|
|
|
>>> si_model = stringIndexer.fit(df)
|
|
|
|
>>> td = si_model.transform(df)
|
|
|
|
>>> gbt = GBTClassifier(maxIter=5, maxDepth=2, labelCol="indexed")
|
|
|
|
>>> model = gbt.fit(td)
|
2015-07-07 11:58:08 -04:00
|
|
|
>>> allclose(model.treeWeights, [1.0, 0.1, 0.1, 0.1, 0.1])
|
|
|
|
True
|
2015-05-13 18:13:09 -04:00
|
|
|
>>> test0 = sqlContext.createDataFrame([(Vectors.dense(-1.0),)], ["features"])
|
|
|
|
>>> model.transform(test0).head().prediction
|
|
|
|
0.0
|
|
|
|
>>> test1 = sqlContext.createDataFrame([(Vectors.sparse(1, [0], [1.0]),)], ["features"])
|
|
|
|
>>> model.transform(test1).head().prediction
|
|
|
|
1.0
|
|
|
|
"""
|
|
|
|
|
|
|
|
# a placeholder to make it appear in the generated doc
|
|
|
|
lossType = Param(Params._dummy(), "lossType",
|
|
|
|
"Loss function which GBT tries to minimize (case-insensitive). " +
|
|
|
|
"Supported options: " + ", ".join(GBTParams.supportedLossTypes))
|
|
|
|
subsamplingRate = Param(Params._dummy(), "subsamplingRate",
|
|
|
|
"Fraction of the training data used for learning each decision tree, " +
|
|
|
|
"in range (0, 1].")
|
|
|
|
stepSize = Param(Params._dummy(), "stepSize",
|
|
|
|
"Step size (a.k.a. learning rate) in interval (0, 1] for shrinking the " +
|
|
|
|
"contribution of each estimator")
|
|
|
|
|
|
|
|
@keyword_only
|
|
|
|
def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction",
|
|
|
|
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
|
|
|
|
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, lossType="logistic",
|
|
|
|
maxIter=20, stepSize=0.1):
|
|
|
|
"""
|
2015-05-14 21:16:22 -04:00
|
|
|
__init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
|
|
|
|
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \
|
|
|
|
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, \
|
|
|
|
lossType="logistic", maxIter=20, stepSize=0.1)
|
2015-05-13 18:13:09 -04:00
|
|
|
"""
|
|
|
|
super(GBTClassifier, self).__init__()
|
2015-05-18 15:02:18 -04:00
|
|
|
self._java_obj = self._new_java_obj(
|
|
|
|
"org.apache.spark.ml.classification.GBTClassifier", self.uid)
|
2015-05-13 18:13:09 -04:00
|
|
|
#: param for Loss function which GBT tries to minimize (case-insensitive).
|
|
|
|
self.lossType = Param(self, "lossType",
|
|
|
|
"Loss function which GBT tries to minimize (case-insensitive). " +
|
|
|
|
"Supported options: " + ", ".join(GBTParams.supportedLossTypes))
|
|
|
|
#: Fraction of the training data used for learning each decision tree, in range (0, 1].
|
|
|
|
self.subsamplingRate = Param(self, "subsamplingRate",
|
|
|
|
"Fraction of the training data used for learning each " +
|
|
|
|
"decision tree, in range (0, 1].")
|
|
|
|
#: Step size (a.k.a. learning rate) in interval (0, 1] for shrinking the contribution of
|
|
|
|
# each estimator
|
|
|
|
self.stepSize = Param(self, "stepSize",
|
|
|
|
"Step size (a.k.a. learning rate) in interval (0, 1] for shrinking " +
|
|
|
|
"the contribution of each estimator")
|
|
|
|
self._setDefault(maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
|
|
|
|
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10,
|
|
|
|
lossType="logistic", maxIter=20, stepSize=0.1)
|
|
|
|
kwargs = self.__init__._input_kwargs
|
|
|
|
self.setParams(**kwargs)
|
|
|
|
|
|
|
|
@keyword_only
|
|
|
|
def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction",
|
|
|
|
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
|
|
|
|
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10,
|
|
|
|
lossType="logistic", maxIter=20, stepSize=0.1):
|
|
|
|
"""
|
2015-05-14 21:16:22 -04:00
|
|
|
setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
|
|
|
|
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \
|
|
|
|
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, \
|
2015-05-13 18:13:09 -04:00
|
|
|
lossType="logistic", maxIter=20, stepSize=0.1)
|
|
|
|
Sets params for Gradient Boosted Tree Classification.
|
|
|
|
"""
|
|
|
|
kwargs = self.setParams._input_kwargs
|
|
|
|
return self._set(**kwargs)
|
|
|
|
|
|
|
|
def _create_model(self, java_model):
|
|
|
|
return GBTClassificationModel(java_model)
|
|
|
|
|
|
|
|
def setLossType(self, value):
|
|
|
|
"""
|
|
|
|
Sets the value of :py:attr:`lossType`.
|
|
|
|
"""
|
2015-05-18 15:02:18 -04:00
|
|
|
self._paramMap[self.lossType] = value
|
2015-05-13 18:13:09 -04:00
|
|
|
return self
|
|
|
|
|
|
|
|
def getLossType(self):
|
|
|
|
"""
|
|
|
|
Gets the value of lossType or its default value.
|
|
|
|
"""
|
|
|
|
return self.getOrDefault(self.lossType)
|
|
|
|
|
|
|
|
def setSubsamplingRate(self, value):
|
|
|
|
"""
|
|
|
|
Sets the value of :py:attr:`subsamplingRate`.
|
|
|
|
"""
|
2015-05-18 15:02:18 -04:00
|
|
|
self._paramMap[self.subsamplingRate] = value
|
2015-05-13 18:13:09 -04:00
|
|
|
return self
|
|
|
|
|
|
|
|
def getSubsamplingRate(self):
|
|
|
|
"""
|
|
|
|
Gets the value of subsamplingRate or its default value.
|
|
|
|
"""
|
|
|
|
return self.getOrDefault(self.subsamplingRate)
|
|
|
|
|
|
|
|
def setStepSize(self, value):
|
|
|
|
"""
|
|
|
|
Sets the value of :py:attr:`stepSize`.
|
|
|
|
"""
|
2015-05-18 15:02:18 -04:00
|
|
|
self._paramMap[self.stepSize] = value
|
2015-05-13 18:13:09 -04:00
|
|
|
return self
|
|
|
|
|
|
|
|
def getStepSize(self):
|
|
|
|
"""
|
|
|
|
Gets the value of stepSize or its default value.
|
|
|
|
"""
|
|
|
|
return self.getOrDefault(self.stepSize)
|
|
|
|
|
|
|
|
|
2015-07-07 11:58:08 -04:00
|
|
|
class GBTClassificationModel(TreeEnsembleModels):
|
2015-05-13 18:13:09 -04:00
|
|
|
"""
|
|
|
|
Model fitted by GBTClassifier.
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
2015-07-31 02:03:48 -04:00
|
|
|
@inherit_doc
|
2015-08-03 01:19:27 -04:00
|
|
|
class NaiveBayes(JavaEstimator, HasFeaturesCol, HasLabelCol, HasPredictionCol, HasProbabilityCol,
|
|
|
|
HasRawPredictionCol):
|
2015-07-31 02:03:48 -04:00
|
|
|
"""
|
|
|
|
Naive Bayes Classifiers.
|
|
|
|
|
|
|
|
>>> from pyspark.sql import Row
|
|
|
|
>>> from pyspark.mllib.linalg import Vectors
|
|
|
|
>>> df = sqlContext.createDataFrame([
|
|
|
|
... Row(label=0.0, features=Vectors.dense([0.0, 0.0])),
|
|
|
|
... Row(label=0.0, features=Vectors.dense([0.0, 1.0])),
|
|
|
|
... Row(label=1.0, features=Vectors.dense([1.0, 0.0]))])
|
|
|
|
>>> nb = NaiveBayes(smoothing=1.0, modelType="multinomial")
|
|
|
|
>>> model = nb.fit(df)
|
|
|
|
>>> model.pi
|
|
|
|
DenseVector([-0.51..., -0.91...])
|
|
|
|
>>> model.theta
|
|
|
|
DenseMatrix(2, 2, [-1.09..., -0.40..., -0.40..., -1.09...], 1)
|
|
|
|
>>> test0 = sc.parallelize([Row(features=Vectors.dense([1.0, 0.0]))]).toDF()
|
2015-08-03 01:19:27 -04:00
|
|
|
>>> result = model.transform(test0).head()
|
|
|
|
>>> result.prediction
|
2015-07-31 02:03:48 -04:00
|
|
|
1.0
|
2015-08-03 01:19:27 -04:00
|
|
|
>>> result.probability
|
|
|
|
DenseVector([0.42..., 0.57...])
|
|
|
|
>>> result.rawPrediction
|
|
|
|
DenseVector([-1.60..., -1.32...])
|
2015-07-31 02:03:48 -04:00
|
|
|
>>> test1 = sc.parallelize([Row(features=Vectors.sparse(2, [0], [1.0]))]).toDF()
|
|
|
|
>>> model.transform(test1).head().prediction
|
|
|
|
1.0
|
|
|
|
"""
|
|
|
|
|
|
|
|
# a placeholder to make it appear in the generated doc
|
|
|
|
smoothing = Param(Params._dummy(), "smoothing", "The smoothing parameter, should be >= 0, " +
|
|
|
|
"default is 1.0")
|
|
|
|
modelType = Param(Params._dummy(), "modelType", "The model type which is a string " +
|
|
|
|
"(case-sensitive). Supported options: multinomial (default) and bernoulli.")
|
|
|
|
|
|
|
|
@keyword_only
|
|
|
|
def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction",
|
2015-08-03 01:19:27 -04:00
|
|
|
probabilityCol="probability", rawPredictionCol="rawPrediction", smoothing=1.0,
|
|
|
|
modelType="multinomial"):
|
2015-07-31 02:03:48 -04:00
|
|
|
"""
|
2015-08-03 01:19:27 -04:00
|
|
|
__init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
|
|
|
|
probabilityCol="probability", rawPredictionCol="rawPrediction", smoothing=1.0, \
|
|
|
|
modelType="multinomial")
|
2015-07-31 02:03:48 -04:00
|
|
|
"""
|
|
|
|
super(NaiveBayes, self).__init__()
|
|
|
|
self._java_obj = self._new_java_obj(
|
|
|
|
"org.apache.spark.ml.classification.NaiveBayes", self.uid)
|
|
|
|
#: param for the smoothing parameter.
|
|
|
|
self.smoothing = Param(self, "smoothing", "The smoothing parameter, should be >= 0, " +
|
|
|
|
"default is 1.0")
|
|
|
|
#: param for the model type.
|
|
|
|
self.modelType = Param(self, "modelType", "The model type which is a string " +
|
|
|
|
"(case-sensitive). Supported options: multinomial (default) " +
|
|
|
|
"and bernoulli.")
|
|
|
|
self._setDefault(smoothing=1.0, modelType="multinomial")
|
|
|
|
kwargs = self.__init__._input_kwargs
|
|
|
|
self.setParams(**kwargs)
|
|
|
|
|
|
|
|
@keyword_only
|
|
|
|
def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction",
|
2015-08-03 01:19:27 -04:00
|
|
|
probabilityCol="probability", rawPredictionCol="rawPrediction", smoothing=1.0,
|
|
|
|
modelType="multinomial"):
|
2015-07-31 02:03:48 -04:00
|
|
|
"""
|
2015-08-03 01:19:27 -04:00
|
|
|
setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
|
|
|
|
probabilityCol="probability", rawPredictionCol="rawPrediction", smoothing=1.0, \
|
|
|
|
modelType="multinomial")
|
2015-07-31 02:03:48 -04:00
|
|
|
Sets params for Naive Bayes.
|
|
|
|
"""
|
|
|
|
kwargs = self.setParams._input_kwargs
|
|
|
|
return self._set(**kwargs)
|
|
|
|
|
|
|
|
def _create_model(self, java_model):
|
|
|
|
return NaiveBayesModel(java_model)
|
|
|
|
|
|
|
|
def setSmoothing(self, value):
|
|
|
|
"""
|
|
|
|
Sets the value of :py:attr:`smoothing`.
|
|
|
|
"""
|
|
|
|
self._paramMap[self.smoothing] = value
|
|
|
|
return self
|
|
|
|
|
|
|
|
def getSmoothing(self):
|
|
|
|
"""
|
|
|
|
Gets the value of smoothing or its default value.
|
|
|
|
"""
|
|
|
|
return self.getOrDefault(self.smoothing)
|
|
|
|
|
|
|
|
def setModelType(self, value):
|
|
|
|
"""
|
|
|
|
Sets the value of :py:attr:`modelType`.
|
|
|
|
"""
|
|
|
|
self._paramMap[self.modelType] = value
|
|
|
|
return self
|
|
|
|
|
|
|
|
def getModelType(self):
|
|
|
|
"""
|
|
|
|
Gets the value of modelType or its default value.
|
|
|
|
"""
|
|
|
|
return self.getOrDefault(self.modelType)
|
|
|
|
|
|
|
|
|
|
|
|
class NaiveBayesModel(JavaModel):
|
|
|
|
"""
|
|
|
|
Model fitted by NaiveBayes.
|
|
|
|
"""
|
|
|
|
|
|
|
|
@property
|
|
|
|
def pi(self):
|
|
|
|
"""
|
|
|
|
log of class priors.
|
|
|
|
"""
|
|
|
|
return self._call_java("pi")
|
|
|
|
|
|
|
|
@property
|
|
|
|
def theta(self):
|
|
|
|
"""
|
|
|
|
log of class conditional probabilities.
|
|
|
|
"""
|
|
|
|
return self._call_java("theta")
|
|
|
|
|
|
|
|
|
2015-01-28 20:14:23 -05:00
|
|
|
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:
|
2015-05-12 15:17:05 -04:00
|
|
|
sc = SparkContext("local[2]", "ml.classification tests")
|
2015-04-08 16:31:45 -04:00
|
|
|
sqlContext = SQLContext(sc)
|
2015-01-28 20:14:23 -05:00
|
|
|
globs['sc'] = sc
|
2015-04-08 16:31:45 -04:00
|
|
|
globs['sqlContext'] = sqlContext
|
2015-01-28 20:14:23 -05:00
|
|
|
(failure_count, test_count) = doctest.testmod(
|
|
|
|
globs=globs, optionflags=doctest.ELLIPSIS)
|
|
|
|
sc.stop()
|
|
|
|
if failure_count:
|
|
|
|
exit(-1)
|