-
Notifications
You must be signed in to change notification settings - Fork 28.3k
/
regression.py
3333 lines (2919 loc) · 99.8 KB
/
regression.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# 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.
#
import sys
from typing import Any, Dict, Generic, List, Optional, TypeVar, TYPE_CHECKING
from abc import ABCMeta
from pyspark import keyword_only, since
from pyspark.ml import Predictor, PredictionModel
from pyspark.ml.base import _PredictorParams
from pyspark.ml.param.shared import (
HasFeaturesCol,
HasLabelCol,
HasPredictionCol,
HasWeightCol,
Param,
Params,
TypeConverters,
HasMaxIter,
HasTol,
HasFitIntercept,
HasAggregationDepth,
HasMaxBlockSizeInMB,
HasRegParam,
HasSolver,
HasStepSize,
HasSeed,
HasElasticNetParam,
HasStandardization,
HasLoss,
HasVarianceCol,
)
from pyspark.ml.tree import (
_DecisionTreeModel,
_DecisionTreeParams,
_TreeEnsembleModel,
_RandomForestParams,
_GBTParams,
_TreeRegressorParams,
)
from pyspark.ml.base import Transformer
from pyspark.ml.linalg import Vector, Matrix
from pyspark.ml.util import (
JavaMLWritable,
JavaMLReadable,
HasTrainingSummary,
GeneralJavaMLWritable,
)
from pyspark.ml.wrapper import (
JavaEstimator,
JavaModel,
JavaPredictor,
JavaPredictionModel,
JavaTransformer,
JavaWrapper,
)
from pyspark.ml.common import inherit_doc
from pyspark.sql import DataFrame
if TYPE_CHECKING:
from py4j.java_gateway import JavaObject
T = TypeVar("T")
M = TypeVar("M", bound=Transformer)
JM = TypeVar("JM", bound=JavaTransformer)
__all__ = [
"AFTSurvivalRegression",
"AFTSurvivalRegressionModel",
"DecisionTreeRegressor",
"DecisionTreeRegressionModel",
"GBTRegressor",
"GBTRegressionModel",
"GeneralizedLinearRegression",
"GeneralizedLinearRegressionModel",
"GeneralizedLinearRegressionSummary",
"GeneralizedLinearRegressionTrainingSummary",
"IsotonicRegression",
"IsotonicRegressionModel",
"LinearRegression",
"LinearRegressionModel",
"LinearRegressionSummary",
"LinearRegressionTrainingSummary",
"RandomForestRegressor",
"RandomForestRegressionModel",
"FMRegressor",
"FMRegressionModel",
]
class Regressor(Predictor[M], _PredictorParams, Generic[M], metaclass=ABCMeta):
"""
Regressor for regression tasks.
.. versionadded:: 3.0.0
"""
pass
class RegressionModel(PredictionModel[T], _PredictorParams, metaclass=ABCMeta):
"""
Model produced by a ``Regressor``.
.. versionadded:: 3.0.0
"""
pass
class _JavaRegressor(Regressor, JavaPredictor[JM], Generic[JM], metaclass=ABCMeta):
"""
Java Regressor for regression tasks.
.. versionadded:: 3.0.0
"""
pass
class _JavaRegressionModel(RegressionModel, JavaPredictionModel[T], metaclass=ABCMeta):
"""
Java Model produced by a ``_JavaRegressor``.
To be mixed in with :class:`pyspark.ml.JavaModel`
.. versionadded:: 3.0.0
"""
pass
class _LinearRegressionParams(
_PredictorParams,
HasRegParam,
HasElasticNetParam,
HasMaxIter,
HasTol,
HasFitIntercept,
HasStandardization,
HasWeightCol,
HasSolver,
HasAggregationDepth,
HasLoss,
HasMaxBlockSizeInMB,
):
"""
Params for :py:class:`LinearRegression` and :py:class:`LinearRegressionModel`.
.. versionadded:: 3.0.0
"""
solver: Param[str] = Param(
Params._dummy(),
"solver",
"The solver algorithm for optimization. Supported " + "options: auto, normal, l-bfgs.",
typeConverter=TypeConverters.toString,
)
loss: Param[str] = Param(
Params._dummy(),
"loss",
"The loss function to be optimized. Supported " + "options: squaredError, huber.",
typeConverter=TypeConverters.toString,
)
epsilon: Param[float] = Param(
Params._dummy(),
"epsilon",
"The shape parameter to control the amount of "
+ "robustness. Must be > 1.0. Only valid when loss is huber",
typeConverter=TypeConverters.toFloat,
)
def __init__(self, *args: Any):
super(_LinearRegressionParams, self).__init__(*args)
self._setDefault(
maxIter=100,
regParam=0.0,
tol=1e-6,
loss="squaredError",
epsilon=1.35,
maxBlockSizeInMB=0.0,
)
@since("2.3.0")
def getEpsilon(self) -> float:
"""
Gets the value of epsilon or its default value.
"""
return self.getOrDefault(self.epsilon)
@inherit_doc
class LinearRegression(
_JavaRegressor["LinearRegressionModel"],
_LinearRegressionParams,
JavaMLWritable,
JavaMLReadable["LinearRegression"],
):
"""
Linear regression.
The learning objective is to minimize the specified loss function, with regularization.
This supports two kinds of loss:
* squaredError (a.k.a squared loss)
* huber (a hybrid of squared error for relatively small errors and absolute error for \
relatively large ones, and we estimate the scale parameter from training data)
This supports multiple types of regularization:
* none (a.k.a. ordinary least squares)
* L2 (ridge regression)
* L1 (Lasso)
* L2 + L1 (elastic net)
.. versionadded:: 1.4.0
Notes
-----
Fitting with huber loss only supports none and L2 regularization.
Examples
--------
>>> from pyspark.ml.linalg import Vectors
>>> df = spark.createDataFrame([
... (1.0, 2.0, Vectors.dense(1.0)),
... (0.0, 2.0, Vectors.sparse(1, [], []))], ["label", "weight", "features"])
>>> lr = LinearRegression(regParam=0.0, solver="normal", weightCol="weight")
>>> lr.setMaxIter(5)
LinearRegression...
>>> lr.getMaxIter()
5
>>> lr.setRegParam(0.1)
LinearRegression...
>>> lr.getRegParam()
0.1
>>> lr.setRegParam(0.0)
LinearRegression...
>>> model = lr.fit(df)
>>> model.setFeaturesCol("features")
LinearRegressionModel...
>>> model.setPredictionCol("newPrediction")
LinearRegressionModel...
>>> model.getMaxIter()
5
>>> model.getMaxBlockSizeInMB()
0.0
>>> test0 = spark.createDataFrame([(Vectors.dense(-1.0),)], ["features"])
>>> abs(model.predict(test0.head().features) - (-1.0)) < 0.001
True
>>> abs(model.transform(test0).head().newPrediction - (-1.0)) < 0.001
True
>>> bool(abs(model.coefficients[0] - 1.0) < 0.001)
True
>>> abs(model.intercept - 0.0) < 0.001
True
>>> test1 = spark.createDataFrame([(Vectors.sparse(1, [0], [1.0]),)], ["features"])
>>> abs(model.transform(test1).head().newPrediction - 1.0) < 0.001
True
>>> lr.setParams(featuresCol="vector")
LinearRegression...
>>> lr_path = temp_path + "/lr"
>>> lr.save(lr_path)
>>> lr2 = LinearRegression.load(lr_path)
>>> lr2.getMaxIter()
5
>>> model_path = temp_path + "/lr_model"
>>> model.save(model_path)
>>> model2 = LinearRegressionModel.load(model_path)
>>> bool(model.coefficients[0] == model2.coefficients[0])
True
>>> bool(model.intercept == model2.intercept)
True
>>> bool(model.transform(test0).take(1) == model2.transform(test0).take(1))
True
>>> model.numFeatures
1
>>> model.write().format("pmml").save(model_path + "_2")
"""
_input_kwargs: Dict[str, Any]
@keyword_only
def __init__(
self,
*,
featuresCol: str = "features",
labelCol: str = "label",
predictionCol: str = "prediction",
maxIter: int = 100,
regParam: float = 0.0,
elasticNetParam: float = 0.0,
tol: float = 1e-6,
fitIntercept: bool = True,
standardization: bool = True,
solver: str = "auto",
weightCol: Optional[str] = None,
aggregationDepth: int = 2,
loss: str = "squaredError",
epsilon: float = 1.35,
maxBlockSizeInMB: float = 0.0,
):
"""
__init__(self, \\*, featuresCol="features", labelCol="label", predictionCol="prediction", \
maxIter=100, regParam=0.0, elasticNetParam=0.0, tol=1e-6, fitIntercept=True, \
standardization=True, solver="auto", weightCol=None, aggregationDepth=2, \
loss="squaredError", epsilon=1.35, maxBlockSizeInMB=0.0)
"""
super(LinearRegression, self).__init__()
self._java_obj = self._new_java_obj(
"org.apache.spark.ml.regression.LinearRegression", self.uid
)
kwargs = self._input_kwargs
self.setParams(**kwargs)
@keyword_only
@since("1.4.0")
def setParams(
self,
*,
featuresCol: str = "features",
labelCol: str = "label",
predictionCol: str = "prediction",
maxIter: int = 100,
regParam: float = 0.0,
elasticNetParam: float = 0.0,
tol: float = 1e-6,
fitIntercept: bool = True,
standardization: bool = True,
solver: str = "auto",
weightCol: Optional[str] = None,
aggregationDepth: int = 2,
loss: str = "squaredError",
epsilon: float = 1.35,
maxBlockSizeInMB: float = 0.0,
) -> "LinearRegression":
"""
setParams(self, \\*, featuresCol="features", labelCol="label", predictionCol="prediction", \
maxIter=100, regParam=0.0, elasticNetParam=0.0, tol=1e-6, fitIntercept=True, \
standardization=True, solver="auto", weightCol=None, aggregationDepth=2, \
loss="squaredError", epsilon=1.35, maxBlockSizeInMB=0.0)
Sets params for linear regression.
"""
kwargs = self._input_kwargs
return self._set(**kwargs)
def _create_model(self, java_model: "JavaObject") -> "LinearRegressionModel":
return LinearRegressionModel(java_model)
@since("2.3.0")
def setEpsilon(self, value: float) -> "LinearRegression":
"""
Sets the value of :py:attr:`epsilon`.
"""
return self._set(epsilon=value)
def setMaxIter(self, value: int) -> "LinearRegression":
"""
Sets the value of :py:attr:`maxIter`.
"""
return self._set(maxIter=value)
def setRegParam(self, value: float) -> "LinearRegression":
"""
Sets the value of :py:attr:`regParam`.
"""
return self._set(regParam=value)
def setTol(self, value: float) -> "LinearRegression":
"""
Sets the value of :py:attr:`tol`.
"""
return self._set(tol=value)
def setElasticNetParam(self, value: float) -> "LinearRegression":
"""
Sets the value of :py:attr:`elasticNetParam`.
"""
return self._set(elasticNetParam=value)
def setFitIntercept(self, value: bool) -> "LinearRegression":
"""
Sets the value of :py:attr:`fitIntercept`.
"""
return self._set(fitIntercept=value)
def setStandardization(self, value: bool) -> "LinearRegression":
"""
Sets the value of :py:attr:`standardization`.
"""
return self._set(standardization=value)
def setWeightCol(self, value: str) -> "LinearRegression":
"""
Sets the value of :py:attr:`weightCol`.
"""
return self._set(weightCol=value)
def setSolver(self, value: str) -> "LinearRegression":
"""
Sets the value of :py:attr:`solver`.
"""
return self._set(solver=value)
def setAggregationDepth(self, value: int) -> "LinearRegression":
"""
Sets the value of :py:attr:`aggregationDepth`.
"""
return self._set(aggregationDepth=value)
def setLoss(self, value: str) -> "LinearRegression":
"""
Sets the value of :py:attr:`loss`.
"""
return self._set(lossType=value)
@since("3.1.0")
def setMaxBlockSizeInMB(self, value: float) -> "LinearRegression":
"""
Sets the value of :py:attr:`maxBlockSizeInMB`.
"""
return self._set(maxBlockSizeInMB=value)
class LinearRegressionModel(
_JavaRegressionModel,
_LinearRegressionParams,
GeneralJavaMLWritable,
JavaMLReadable["LinearRegressionModel"],
HasTrainingSummary["LinearRegressionSummary"],
):
"""
Model fitted by :class:`LinearRegression`.
.. versionadded:: 1.4.0
"""
@property
@since("2.0.0")
def coefficients(self) -> Vector:
"""
Model coefficients.
"""
return self._call_java("coefficients")
@property
@since("1.4.0")
def intercept(self) -> float:
"""
Model intercept.
"""
return self._call_java("intercept")
@property
@since("2.3.0")
def scale(self) -> float:
r"""
The value by which :math:`\|y - X'w\|` is scaled down when loss is "huber", otherwise 1.0.
"""
return self._call_java("scale")
@property
@since("2.0.0")
def summary(self) -> "LinearRegressionTrainingSummary":
"""
Gets summary (residuals, MSE, r-squared ) of model on
training set. An exception is thrown if
`trainingSummary is None`.
"""
if self.hasSummary:
return LinearRegressionTrainingSummary(super(LinearRegressionModel, self).summary)
else:
raise RuntimeError(
"No training summary available for this %s" % self.__class__.__name__
)
def evaluate(self, dataset: DataFrame) -> "LinearRegressionSummary":
"""
Evaluates the model on a test dataset.
.. versionadded:: 2.0.0
Parameters
----------
dataset : :py:class:`pyspark.sql.DataFrame`
Test dataset to evaluate model on, where dataset is an
instance of :py:class:`pyspark.sql.DataFrame`
"""
if not isinstance(dataset, DataFrame):
raise TypeError("dataset must be a DataFrame but got %s." % type(dataset))
java_lr_summary = self._call_java("evaluate", dataset)
return LinearRegressionSummary(java_lr_summary)
class LinearRegressionSummary(JavaWrapper):
"""
Linear regression results evaluated on a dataset.
.. versionadded:: 2.0.0
"""
@property
@since("2.0.0")
def predictions(self) -> DataFrame:
"""
Dataframe outputted by the model's `transform` method.
"""
return self._call_java("predictions")
@property
@since("2.0.0")
def predictionCol(self) -> str:
"""
Field in "predictions" which gives the predicted value of
the label at each instance.
"""
return self._call_java("predictionCol")
@property
@since("2.0.0")
def labelCol(self) -> str:
"""
Field in "predictions" which gives the true label of each
instance.
"""
return self._call_java("labelCol")
@property
@since("2.0.0")
def featuresCol(self) -> str:
"""
Field in "predictions" which gives the features of each instance
as a vector.
"""
return self._call_java("featuresCol")
@property
@since("2.0.0")
def explainedVariance(self) -> float:
r"""
Returns the explained variance regression score.
explainedVariance = :math:`1 - \frac{variance(y - \hat{y})}{variance(y)}`
Notes
-----
This ignores instance weights (setting all to 1.0) from
`LinearRegression.weightCol`. This will change in later Spark
versions.
For additional information see
`Explained variation on Wikipedia \
<http://en.wikipedia.org/wiki/Explained_variation>`_
"""
return self._call_java("explainedVariance")
@property
@since("2.0.0")
def meanAbsoluteError(self) -> float:
"""
Returns the mean absolute error, which is a risk function
corresponding to the expected value of the absolute error
loss or l1-norm loss.
Notes
-----
This ignores instance weights (setting all to 1.0) from
`LinearRegression.weightCol`. This will change in later Spark
versions.
"""
return self._call_java("meanAbsoluteError")
@property
@since("2.0.0")
def meanSquaredError(self) -> float:
"""
Returns the mean squared error, which is a risk function
corresponding to the expected value of the squared error
loss or quadratic loss.
Notes
-----
This ignores instance weights (setting all to 1.0) from
`LinearRegression.weightCol`. This will change in later Spark
versions.
"""
return self._call_java("meanSquaredError")
@property
@since("2.0.0")
def rootMeanSquaredError(self) -> float:
"""
Returns the root mean squared error, which is defined as the
square root of the mean squared error.
Notes
-----
This ignores instance weights (setting all to 1.0) from
`LinearRegression.weightCol`. This will change in later Spark
versions.
"""
return self._call_java("rootMeanSquaredError")
@property
@since("2.0.0")
def r2(self) -> float:
"""
Returns R^2, the coefficient of determination.
Notes
-----
This ignores instance weights (setting all to 1.0) from
`LinearRegression.weightCol`. This will change in later Spark
versions.
See also `Wikipedia coefficient of determination \
<http://en.wikipedia.org/wiki/Coefficient_of_determination>`_
"""
return self._call_java("r2")
@property
@since("2.4.0")
def r2adj(self) -> float:
"""
Returns Adjusted R^2, the adjusted coefficient of determination.
Notes
-----
This ignores instance weights (setting all to 1.0) from
`LinearRegression.weightCol`. This will change in later Spark versions.
`Wikipedia coefficient of determination, Adjusted R^2 \
<https://en.wikipedia.org/wiki/Coefficient_of_determination#Adjusted_R2>`_
"""
return self._call_java("r2adj")
@property
@since("2.0.0")
def residuals(self) -> DataFrame:
"""
Residuals (label - predicted value)
"""
return self._call_java("residuals")
@property
@since("2.0.0")
def numInstances(self) -> int:
"""
Number of instances in DataFrame predictions
"""
return self._call_java("numInstances")
@property
@since("2.2.0")
def degreesOfFreedom(self) -> int:
"""
Degrees of freedom.
"""
return self._call_java("degreesOfFreedom")
@property
@since("2.0.0")
def devianceResiduals(self) -> List[float]:
"""
The weighted residuals, the usual residuals rescaled by the
square root of the instance weights.
"""
return self._call_java("devianceResiduals")
@property
def coefficientStandardErrors(self) -> List[float]:
"""
Standard error of estimated coefficients and intercept.
This value is only available when using the "normal" solver.
If :py:attr:`LinearRegression.fitIntercept` is set to True,
then the last element returned corresponds to the intercept.
.. versionadded:: 2.0.0
See Also
--------
LinearRegression.solver
"""
return self._call_java("coefficientStandardErrors")
@property
def tValues(self) -> List[float]:
"""
T-statistic of estimated coefficients and intercept.
This value is only available when using the "normal" solver.
If :py:attr:`LinearRegression.fitIntercept` is set to True,
then the last element returned corresponds to the intercept.
.. versionadded:: 2.0.0
See Also
--------
LinearRegression.solver
"""
return self._call_java("tValues")
@property
def pValues(self) -> List[float]:
"""
Two-sided p-value of estimated coefficients and intercept.
This value is only available when using the "normal" solver.
If :py:attr:`LinearRegression.fitIntercept` is set to True,
then the last element returned corresponds to the intercept.
.. versionadded:: 2.0.0
See Also
--------
LinearRegression.solver
"""
return self._call_java("pValues")
@inherit_doc
class LinearRegressionTrainingSummary(LinearRegressionSummary):
"""
Linear regression training results. Currently, the training summary ignores the
training weights except for the objective trace.
.. versionadded:: 2.0.0
"""
@property
def objectiveHistory(self) -> List[float]:
"""
Objective function (scaled loss + regularization) at each
iteration.
This value is only available when using the "l-bfgs" solver.
.. versionadded:: 2.0.0
See Also
--------
LinearRegression.solver
"""
return self._call_java("objectiveHistory")
@property
def totalIterations(self) -> int:
"""
Number of training iterations until termination.
This value is only available when using the "l-bfgs" solver.
.. versionadded:: 2.0.0
See Also
--------
LinearRegression.solver
"""
return self._call_java("totalIterations")
class _IsotonicRegressionParams(HasFeaturesCol, HasLabelCol, HasPredictionCol, HasWeightCol):
"""
Params for :py:class:`IsotonicRegression` and :py:class:`IsotonicRegressionModel`.
.. versionadded:: 3.0.0
"""
isotonic: Param[bool] = Param(
Params._dummy(),
"isotonic",
"whether the output sequence should be isotonic/increasing (true) or"
+ "antitonic/decreasing (false).",
typeConverter=TypeConverters.toBoolean,
)
featureIndex: Param[int] = Param(
Params._dummy(),
"featureIndex",
"The index of the feature if featuresCol is a vector column, no effect otherwise.",
typeConverter=TypeConverters.toInt,
)
def __init__(self, *args: Any):
super(_IsotonicRegressionParams, self).__init__(*args)
self._setDefault(isotonic=True, featureIndex=0)
def getIsotonic(self) -> bool:
"""
Gets the value of isotonic or its default value.
"""
return self.getOrDefault(self.isotonic)
def getFeatureIndex(self) -> int:
"""
Gets the value of featureIndex or its default value.
"""
return self.getOrDefault(self.featureIndex)
@inherit_doc
class IsotonicRegression(
JavaEstimator, _IsotonicRegressionParams, HasWeightCol, JavaMLWritable, JavaMLReadable
):
"""
Currently implemented using parallelized pool adjacent violators algorithm.
Only univariate (single feature) algorithm supported.
.. versionadded:: 1.6.0
Examples
--------
>>> from pyspark.ml.linalg import Vectors
>>> df = spark.createDataFrame([
... (1.0, Vectors.dense(1.0)),
... (0.0, Vectors.sparse(1, [], []))], ["label", "features"])
>>> ir = IsotonicRegression()
>>> model = ir.fit(df)
>>> model.setFeaturesCol("features")
IsotonicRegressionModel...
>>> model.numFeatures
1
>>> test0 = spark.createDataFrame([(Vectors.dense(-1.0),)], ["features"])
>>> model.transform(test0).head().prediction
0.0
>>> model.predict(test0.head().features[model.getFeatureIndex()])
0.0
>>> model.boundaries
DenseVector([0.0, 1.0])
>>> ir_path = temp_path + "/ir"
>>> ir.save(ir_path)
>>> ir2 = IsotonicRegression.load(ir_path)
>>> ir2.getIsotonic()
True
>>> model_path = temp_path + "/ir_model"
>>> model.save(model_path)
>>> model2 = IsotonicRegressionModel.load(model_path)
>>> model.boundaries == model2.boundaries
True
>>> model.predictions == model2.predictions
True
>>> model.transform(test0).take(1) == model2.transform(test0).take(1)
True
"""
_input_kwargs: Dict[str, Any]
@keyword_only
def __init__(
self,
*,
featuresCol: str = "features",
labelCol: str = "label",
predictionCol: str = "prediction",
weightCol: Optional[str] = None,
isotonic: bool = True,
featureIndex: int = 0,
):
"""
__init__(self, \\*, featuresCol="features", labelCol="label", predictionCol="prediction", \
weightCol=None, isotonic=True, featureIndex=0):
"""
super(IsotonicRegression, self).__init__()
self._java_obj = self._new_java_obj(
"org.apache.spark.ml.regression.IsotonicRegression", self.uid
)
kwargs = self._input_kwargs
self.setParams(**kwargs)
@keyword_only
def setParams(
self,
*,
featuresCol: str = "features",
labelCol: str = "label",
predictionCol: str = "prediction",
weightCol: Optional[str] = None,
isotonic: bool = True,
featureIndex: int = 0,
) -> "IsotonicRegression":
"""
setParams(self, \\*, featuresCol="features", labelCol="label", predictionCol="prediction", \
weightCol=None, isotonic=True, featureIndex=0):
Set the params for IsotonicRegression.
"""
kwargs = self._input_kwargs
return self._set(**kwargs)
def _create_model(self, java_model: "JavaObject") -> "IsotonicRegressionModel":
return IsotonicRegressionModel(java_model)
def setIsotonic(self, value: bool) -> "IsotonicRegression":
"""
Sets the value of :py:attr:`isotonic`.
"""
return self._set(isotonic=value)
def setFeatureIndex(self, value: int) -> "IsotonicRegression":
"""
Sets the value of :py:attr:`featureIndex`.
"""
return self._set(featureIndex=value)
@since("1.6.0")
def setFeaturesCol(self, value: str) -> "IsotonicRegression":
"""
Sets the value of :py:attr:`featuresCol`.
"""
return self._set(featuresCol=value)
@since("1.6.0")
def setPredictionCol(self, value: str) -> "IsotonicRegression":
"""
Sets the value of :py:attr:`predictionCol`.
"""
return self._set(predictionCol=value)
@since("1.6.0")
def setLabelCol(self, value: str) -> "IsotonicRegression":
"""
Sets the value of :py:attr:`labelCol`.
"""
return self._set(labelCol=value)
@since("1.6.0")
def setWeightCol(self, value: str) -> "IsotonicRegression":
"""
Sets the value of :py:attr:`weightCol`.
"""
return self._set(weightCol=value)
class IsotonicRegressionModel(
JavaModel,
_IsotonicRegressionParams,
JavaMLWritable,
JavaMLReadable["IsotonicRegressionModel"],
):
"""
Model fitted by :class:`IsotonicRegression`.
.. versionadded:: 1.6.0
"""
@since("3.0.0")
def setFeaturesCol(self, value: str) -> "IsotonicRegressionModel":
"""
Sets the value of :py:attr:`featuresCol`.
"""
return self._set(featuresCol=value)
@since("3.0.0")
def setPredictionCol(self, value: str) -> "IsotonicRegressionModel":
"""
Sets the value of :py:attr:`predictionCol`.
"""
return self._set(predictionCol=value)
def setFeatureIndex(self, value: int) -> "IsotonicRegressionModel":
"""
Sets the value of :py:attr:`featureIndex`.
"""
return self._set(featureIndex=value)
@property
@since("1.6.0")
def boundaries(self) -> Vector:
"""
Boundaries in increasing order for which predictions are known.
"""
return self._call_java("boundaries")
@property
@since("1.6.0")
def predictions(self) -> Vector:
"""
Predictions associated with the boundaries at the same index, monotone because of isotonic
regression.
"""
return self._call_java("predictions")
@property
@since("3.0.0")
def numFeatures(self) -> int:
"""
Returns the number of features the model was trained on. If unknown, returns -1
"""