Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

# 

# 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 abc import abstractmethod, ABCMeta 

 

from pyspark import since, keyword_only 

from pyspark.ml.wrapper import JavaParams 

from pyspark.ml.param import Param, Params, TypeConverters 

from pyspark.ml.param.shared import HasLabelCol, HasPredictionCol, HasProbabilityCol, \ 

HasRawPredictionCol, HasFeaturesCol, HasWeightCol 

from pyspark.ml.common import inherit_doc 

from pyspark.ml.util import JavaMLReadable, JavaMLWritable 

 

__all__ = ['Evaluator', 'BinaryClassificationEvaluator', 'RegressionEvaluator', 

'MulticlassClassificationEvaluator', 'MultilabelClassificationEvaluator', 

'ClusteringEvaluator', 'RankingEvaluator'] 

 

 

@inherit_doc 

class Evaluator(Params, metaclass=ABCMeta): 

""" 

Base class for evaluators that compute metrics from predictions. 

 

.. versionadded:: 1.4.0 

""" 

pass 

 

@abstractmethod 

def _evaluate(self, dataset): 

""" 

Evaluates the output. 

 

Parameters 

---------- 

dataset : :py:class:`pyspark.sql.DataFrame` 

a dataset that contains labels/observations and predictions 

 

Returns 

------- 

float 

metric 

""" 

raise NotImplementedError() 

 

def evaluate(self, dataset, params=None): 

""" 

Evaluates the output with optional parameters. 

 

.. versionadded:: 1.4.0 

 

Parameters 

---------- 

dataset : :py:class:`pyspark.sql.DataFrame` 

a dataset that contains labels/observations and predictions 

params : dict, optional 

an optional param map that overrides embedded params 

 

Returns 

------- 

float 

metric 

""" 

if params is None: 

params = dict() 

if isinstance(params, dict): 

if params: 

return self.copy(params)._evaluate(dataset) 

else: 

return self._evaluate(dataset) 

else: 

raise TypeError("Params must be a param map but got %s." % type(params)) 

 

@since("1.5.0") 

def isLargerBetter(self): 

""" 

Indicates whether the metric returned by :py:meth:`evaluate` should be maximized 

(True, default) or minimized (False). 

A given evaluator may support multiple metrics which may be maximized or minimized. 

""" 

return True 

 

 

@inherit_doc 

class JavaEvaluator(JavaParams, Evaluator, metaclass=ABCMeta): 

""" 

Base class for :py:class:`Evaluator`s that wrap Java/Scala 

implementations. 

""" 

 

def _evaluate(self, dataset): 

""" 

Evaluates the output. 

 

Parameters 

---------- 

dataset : :py:class:`pyspark.sql.DataFrame` 

a dataset that contains labels/observations and predictions 

 

Returns 

------- 

float 

evaluation metric 

""" 

self._transfer_params_to_java() 

return self._java_obj.evaluate(dataset._jdf) 

 

def isLargerBetter(self): 

self._transfer_params_to_java() 

return self._java_obj.isLargerBetter() 

 

 

@inherit_doc 

class BinaryClassificationEvaluator(JavaEvaluator, HasLabelCol, HasRawPredictionCol, HasWeightCol, 

JavaMLReadable, JavaMLWritable): 

""" 

Evaluator for binary classification, which expects input columns rawPrediction, label 

and an optional weight column. 

The rawPrediction column can be of type double (binary 0/1 prediction, or probability of label 

1) or of type vector (length-2 vector of raw predictions, scores, or label probabilities). 

 

.. versionadded:: 1.4.0 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

>>> scoreAndLabels = map(lambda x: (Vectors.dense([1.0 - x[0], x[0]]), x[1]), 

... [(0.1, 0.0), (0.1, 1.0), (0.4, 0.0), (0.6, 0.0), (0.6, 1.0), (0.6, 1.0), (0.8, 1.0)]) 

>>> dataset = spark.createDataFrame(scoreAndLabels, ["raw", "label"]) 

... 

>>> evaluator = BinaryClassificationEvaluator() 

>>> evaluator.setRawPredictionCol("raw") 

BinaryClassificationEvaluator... 

>>> evaluator.evaluate(dataset) 

0.70... 

>>> evaluator.evaluate(dataset, {evaluator.metricName: "areaUnderPR"}) 

0.83... 

>>> bce_path = temp_path + "/bce" 

>>> evaluator.save(bce_path) 

>>> evaluator2 = BinaryClassificationEvaluator.load(bce_path) 

>>> str(evaluator2.getRawPredictionCol()) 

'raw' 

>>> scoreAndLabelsAndWeight = map(lambda x: (Vectors.dense([1.0 - x[0], x[0]]), x[1], x[2]), 

... [(0.1, 0.0, 1.0), (0.1, 1.0, 0.9), (0.4, 0.0, 0.7), (0.6, 0.0, 0.9), 

... (0.6, 1.0, 1.0), (0.6, 1.0, 0.3), (0.8, 1.0, 1.0)]) 

>>> dataset = spark.createDataFrame(scoreAndLabelsAndWeight, ["raw", "label", "weight"]) 

... 

>>> evaluator = BinaryClassificationEvaluator(rawPredictionCol="raw", weightCol="weight") 

>>> evaluator.evaluate(dataset) 

0.70... 

>>> evaluator.evaluate(dataset, {evaluator.metricName: "areaUnderPR"}) 

0.82... 

>>> evaluator.getNumBins() 

1000 

""" 

 

metricName = Param(Params._dummy(), "metricName", 

"metric name in evaluation (areaUnderROC|areaUnderPR)", 

typeConverter=TypeConverters.toString) 

 

numBins = Param(Params._dummy(), "numBins", "Number of bins to down-sample the curves " 

"(ROC curve, PR curve) in area computation. If 0, no down-sampling will " 

"occur. Must be >= 0.", 

typeConverter=TypeConverters.toInt) 

 

@keyword_only 

def __init__(self, *, rawPredictionCol="rawPrediction", labelCol="label", 

metricName="areaUnderROC", weightCol=None, numBins=1000): 

""" 

__init__(self, \\*, rawPredictionCol="rawPrediction", labelCol="label", \ 

metricName="areaUnderROC", weightCol=None, numBins=1000) 

""" 

super(BinaryClassificationEvaluator, self).__init__() 

self._java_obj = self._new_java_obj( 

"org.apache.spark.ml.evaluation.BinaryClassificationEvaluator", self.uid) 

self._setDefault(metricName="areaUnderROC", numBins=1000) 

kwargs = self._input_kwargs 

self._set(**kwargs) 

 

@since("1.4.0") 

def setMetricName(self, value): 

""" 

Sets the value of :py:attr:`metricName`. 

""" 

return self._set(metricName=value) 

 

@since("1.4.0") 

def getMetricName(self): 

""" 

Gets the value of metricName or its default value. 

""" 

return self.getOrDefault(self.metricName) 

 

@since("3.0.0") 

def setNumBins(self, value): 

""" 

Sets the value of :py:attr:`numBins`. 

""" 

return self._set(numBins=value) 

 

@since("3.0.0") 

def getNumBins(self): 

""" 

Gets the value of numBins or its default value. 

""" 

return self.getOrDefault(self.numBins) 

 

def setLabelCol(self, value): 

""" 

Sets the value of :py:attr:`labelCol`. 

""" 

return self._set(labelCol=value) 

 

def setRawPredictionCol(self, value): 

""" 

Sets the value of :py:attr:`rawPredictionCol`. 

""" 

return self._set(rawPredictionCol=value) 

 

@since("3.0.0") 

def setWeightCol(self, value): 

""" 

Sets the value of :py:attr:`weightCol`. 

""" 

return self._set(weightCol=value) 

 

@keyword_only 

@since("1.4.0") 

def setParams(self, *, rawPredictionCol="rawPrediction", labelCol="label", 

metricName="areaUnderROC", weightCol=None, numBins=1000): 

""" 

setParams(self, \\*, rawPredictionCol="rawPrediction", labelCol="label", \ 

metricName="areaUnderROC", weightCol=None, numBins=1000) 

Sets params for binary classification evaluator. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

 

@inherit_doc 

class RegressionEvaluator(JavaEvaluator, HasLabelCol, HasPredictionCol, HasWeightCol, 

JavaMLReadable, JavaMLWritable): 

""" 

Evaluator for Regression, which expects input columns prediction, label 

and an optional weight column. 

 

.. versionadded:: 1.4.0 

 

Examples 

-------- 

>>> scoreAndLabels = [(-28.98343821, -27.0), (20.21491975, 21.5), 

... (-25.98418959, -22.0), (30.69731842, 33.0), (74.69283752, 71.0)] 

>>> dataset = spark.createDataFrame(scoreAndLabels, ["raw", "label"]) 

... 

>>> evaluator = RegressionEvaluator() 

>>> evaluator.setPredictionCol("raw") 

RegressionEvaluator... 

>>> evaluator.evaluate(dataset) 

2.842... 

>>> evaluator.evaluate(dataset, {evaluator.metricName: "r2"}) 

0.993... 

>>> evaluator.evaluate(dataset, {evaluator.metricName: "mae"}) 

2.649... 

>>> re_path = temp_path + "/re" 

>>> evaluator.save(re_path) 

>>> evaluator2 = RegressionEvaluator.load(re_path) 

>>> str(evaluator2.getPredictionCol()) 

'raw' 

>>> scoreAndLabelsAndWeight = [(-28.98343821, -27.0, 1.0), (20.21491975, 21.5, 0.8), 

... (-25.98418959, -22.0, 1.0), (30.69731842, 33.0, 0.6), (74.69283752, 71.0, 0.2)] 

>>> dataset = spark.createDataFrame(scoreAndLabelsAndWeight, ["raw", "label", "weight"]) 

... 

>>> evaluator = RegressionEvaluator(predictionCol="raw", weightCol="weight") 

>>> evaluator.evaluate(dataset) 

2.740... 

>>> evaluator.getThroughOrigin() 

False 

""" 

metricName = Param(Params._dummy(), "metricName", 

"""metric name in evaluation - one of: 

rmse - root mean squared error (default) 

mse - mean squared error 

r2 - r^2 metric 

mae - mean absolute error 

var - explained variance.""", 

typeConverter=TypeConverters.toString) 

 

throughOrigin = Param(Params._dummy(), "throughOrigin", 

"whether the regression is through the origin.", 

typeConverter=TypeConverters.toBoolean) 

 

@keyword_only 

def __init__(self, *, predictionCol="prediction", labelCol="label", 

metricName="rmse", weightCol=None, throughOrigin=False): 

""" 

__init__(self, \\*, predictionCol="prediction", labelCol="label", \ 

metricName="rmse", weightCol=None, throughOrigin=False) 

""" 

super(RegressionEvaluator, self).__init__() 

self._java_obj = self._new_java_obj( 

"org.apache.spark.ml.evaluation.RegressionEvaluator", self.uid) 

self._setDefault(metricName="rmse", throughOrigin=False) 

kwargs = self._input_kwargs 

self._set(**kwargs) 

 

@since("1.4.0") 

def setMetricName(self, value): 

""" 

Sets the value of :py:attr:`metricName`. 

""" 

return self._set(metricName=value) 

 

@since("1.4.0") 

def getMetricName(self): 

""" 

Gets the value of metricName or its default value. 

""" 

return self.getOrDefault(self.metricName) 

 

@since("3.0.0") 

def setThroughOrigin(self, value): 

""" 

Sets the value of :py:attr:`throughOrigin`. 

""" 

return self._set(throughOrigin=value) 

 

@since("3.0.0") 

def getThroughOrigin(self): 

""" 

Gets the value of throughOrigin or its default value. 

""" 

return self.getOrDefault(self.throughOrigin) 

 

def setLabelCol(self, value): 

""" 

Sets the value of :py:attr:`labelCol`. 

""" 

return self._set(labelCol=value) 

 

def setPredictionCol(self, value): 

""" 

Sets the value of :py:attr:`predictionCol`. 

""" 

return self._set(predictionCol=value) 

 

@since("3.0.0") 

def setWeightCol(self, value): 

""" 

Sets the value of :py:attr:`weightCol`. 

""" 

return self._set(weightCol=value) 

 

@keyword_only 

@since("1.4.0") 

def setParams(self, *, predictionCol="prediction", labelCol="label", 

metricName="rmse", weightCol=None, throughOrigin=False): 

""" 

setParams(self, \\*, predictionCol="prediction", labelCol="label", \ 

metricName="rmse", weightCol=None, throughOrigin=False) 

Sets params for regression evaluator. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

 

@inherit_doc 

class MulticlassClassificationEvaluator(JavaEvaluator, HasLabelCol, HasPredictionCol, HasWeightCol, 

HasProbabilityCol, JavaMLReadable, JavaMLWritable): 

""" 

Evaluator for Multiclass Classification, which expects input 

columns: prediction, label, weight (optional) and probabilityCol (only for logLoss). 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> scoreAndLabels = [(0.0, 0.0), (0.0, 1.0), (0.0, 0.0), 

... (1.0, 0.0), (1.0, 1.0), (1.0, 1.0), (1.0, 1.0), (2.0, 2.0), (2.0, 0.0)] 

>>> dataset = spark.createDataFrame(scoreAndLabels, ["prediction", "label"]) 

>>> evaluator = MulticlassClassificationEvaluator() 

>>> evaluator.setPredictionCol("prediction") 

MulticlassClassificationEvaluator... 

>>> evaluator.evaluate(dataset) 

0.66... 

>>> evaluator.evaluate(dataset, {evaluator.metricName: "accuracy"}) 

0.66... 

>>> evaluator.evaluate(dataset, {evaluator.metricName: "truePositiveRateByLabel", 

... evaluator.metricLabel: 1.0}) 

0.75... 

>>> evaluator.setMetricName("hammingLoss") 

MulticlassClassificationEvaluator... 

>>> evaluator.evaluate(dataset) 

0.33... 

>>> mce_path = temp_path + "/mce" 

>>> evaluator.save(mce_path) 

>>> evaluator2 = MulticlassClassificationEvaluator.load(mce_path) 

>>> str(evaluator2.getPredictionCol()) 

'prediction' 

>>> scoreAndLabelsAndWeight = [(0.0, 0.0, 1.0), (0.0, 1.0, 1.0), (0.0, 0.0, 1.0), 

... (1.0, 0.0, 1.0), (1.0, 1.0, 1.0), (1.0, 1.0, 1.0), (1.0, 1.0, 1.0), 

... (2.0, 2.0, 1.0), (2.0, 0.0, 1.0)] 

>>> dataset = spark.createDataFrame(scoreAndLabelsAndWeight, ["prediction", "label", "weight"]) 

>>> evaluator = MulticlassClassificationEvaluator(predictionCol="prediction", 

... weightCol="weight") 

>>> evaluator.evaluate(dataset) 

0.66... 

>>> evaluator.evaluate(dataset, {evaluator.metricName: "accuracy"}) 

0.66... 

>>> predictionAndLabelsWithProbabilities = [ 

... (1.0, 1.0, 1.0, [0.1, 0.8, 0.1]), (0.0, 2.0, 1.0, [0.9, 0.05, 0.05]), 

... (0.0, 0.0, 1.0, [0.8, 0.2, 0.0]), (1.0, 1.0, 1.0, [0.3, 0.65, 0.05])] 

>>> dataset = spark.createDataFrame(predictionAndLabelsWithProbabilities, ["prediction", 

... "label", "weight", "probability"]) 

>>> evaluator = MulticlassClassificationEvaluator(predictionCol="prediction", 

... probabilityCol="probability") 

>>> evaluator.setMetricName("logLoss") 

MulticlassClassificationEvaluator... 

>>> evaluator.evaluate(dataset) 

0.9682... 

""" 

metricName = Param(Params._dummy(), "metricName", 

"metric name in evaluation " 

"(f1|accuracy|weightedPrecision|weightedRecall|weightedTruePositiveRate| " 

"weightedFalsePositiveRate|weightedFMeasure|truePositiveRateByLabel| " 

"falsePositiveRateByLabel|precisionByLabel|recallByLabel|fMeasureByLabel| " 

"logLoss|hammingLoss)", 

typeConverter=TypeConverters.toString) 

metricLabel = Param(Params._dummy(), "metricLabel", 

"The class whose metric will be computed in truePositiveRateByLabel|" 

"falsePositiveRateByLabel|precisionByLabel|recallByLabel|fMeasureByLabel." 

" Must be >= 0. The default value is 0.", 

typeConverter=TypeConverters.toFloat) 

beta = Param(Params._dummy(), "beta", 

"The beta value used in weightedFMeasure|fMeasureByLabel." 

" Must be > 0. The default value is 1.", 

typeConverter=TypeConverters.toFloat) 

eps = Param(Params._dummy(), "eps", 

"log-loss is undefined for p=0 or p=1, so probabilities are clipped to " 

"max(eps, min(1 - eps, p)). " 

"Must be in range (0, 0.5). The default value is 1e-15.", 

typeConverter=TypeConverters.toFloat) 

 

@keyword_only 

def __init__(self, *, predictionCol="prediction", labelCol="label", 

metricName="f1", weightCol=None, metricLabel=0.0, beta=1.0, 

probabilityCol="probability", eps=1e-15): 

""" 

__init__(self, \\*, predictionCol="prediction", labelCol="label", \ 

metricName="f1", weightCol=None, metricLabel=0.0, beta=1.0, \ 

probabilityCol="probability", eps=1e-15) 

""" 

super(MulticlassClassificationEvaluator, self).__init__() 

self._java_obj = self._new_java_obj( 

"org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator", self.uid) 

self._setDefault(metricName="f1", metricLabel=0.0, beta=1.0, eps=1e-15) 

kwargs = self._input_kwargs 

self._set(**kwargs) 

 

@since("1.5.0") 

def setMetricName(self, value): 

""" 

Sets the value of :py:attr:`metricName`. 

""" 

return self._set(metricName=value) 

 

@since("1.5.0") 

def getMetricName(self): 

""" 

Gets the value of metricName or its default value. 

""" 

return self.getOrDefault(self.metricName) 

 

@since("3.0.0") 

def setMetricLabel(self, value): 

""" 

Sets the value of :py:attr:`metricLabel`. 

""" 

return self._set(metricLabel=value) 

 

@since("3.0.0") 

def getMetricLabel(self): 

""" 

Gets the value of metricLabel or its default value. 

""" 

return self.getOrDefault(self.metricLabel) 

 

@since("3.0.0") 

def setBeta(self, value): 

""" 

Sets the value of :py:attr:`beta`. 

""" 

return self._set(beta=value) 

 

@since("3.0.0") 

def getBeta(self): 

""" 

Gets the value of beta or its default value. 

""" 

return self.getOrDefault(self.beta) 

 

@since("3.0.0") 

def setEps(self, value): 

""" 

Sets the value of :py:attr:`eps`. 

""" 

return self._set(eps=value) 

 

@since("3.0.0") 

def getEps(self): 

""" 

Gets the value of eps or its default value. 

""" 

return self.getOrDefault(self.eps) 

 

def setLabelCol(self, value): 

""" 

Sets the value of :py:attr:`labelCol`. 

""" 

return self._set(labelCol=value) 

 

def setPredictionCol(self, value): 

""" 

Sets the value of :py:attr:`predictionCol`. 

""" 

return self._set(predictionCol=value) 

 

@since("3.0.0") 

def setProbabilityCol(self, value): 

""" 

Sets the value of :py:attr:`probabilityCol`. 

""" 

return self._set(probabilityCol=value) 

 

@since("3.0.0") 

def setWeightCol(self, value): 

""" 

Sets the value of :py:attr:`weightCol`. 

""" 

return self._set(weightCol=value) 

 

@keyword_only 

@since("1.5.0") 

def setParams(self, *, predictionCol="prediction", labelCol="label", 

metricName="f1", weightCol=None, metricLabel=0.0, beta=1.0, 

probabilityCol="probability", eps=1e-15): 

""" 

setParams(self, \\*, predictionCol="prediction", labelCol="label", \ 

metricName="f1", weightCol=None, metricLabel=0.0, beta=1.0, \ 

probabilityCol="probability", eps=1e-15) 

Sets params for multiclass classification evaluator. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

 

@inherit_doc 

class MultilabelClassificationEvaluator(JavaEvaluator, HasLabelCol, HasPredictionCol, 

JavaMLReadable, JavaMLWritable): 

""" 

Evaluator for Multilabel Classification, which expects two input 

columns: prediction and label. 

 

.. versionadded:: 3.0.0 

 

Notes 

----- 

Experimental 

 

Examples 

-------- 

>>> scoreAndLabels = [([0.0, 1.0], [0.0, 2.0]), ([0.0, 2.0], [0.0, 1.0]), 

... ([], [0.0]), ([2.0], [2.0]), ([2.0, 0.0], [2.0, 0.0]), 

... ([0.0, 1.0, 2.0], [0.0, 1.0]), ([1.0], [1.0, 2.0])] 

>>> dataset = spark.createDataFrame(scoreAndLabels, ["prediction", "label"]) 

... 

>>> evaluator = MultilabelClassificationEvaluator() 

>>> evaluator.setPredictionCol("prediction") 

MultilabelClassificationEvaluator... 

>>> evaluator.evaluate(dataset) 

0.63... 

>>> evaluator.evaluate(dataset, {evaluator.metricName: "accuracy"}) 

0.54... 

>>> mlce_path = temp_path + "/mlce" 

>>> evaluator.save(mlce_path) 

>>> evaluator2 = MultilabelClassificationEvaluator.load(mlce_path) 

>>> str(evaluator2.getPredictionCol()) 

'prediction' 

""" 

metricName = Param(Params._dummy(), "metricName", 

"metric name in evaluation " 

"(subsetAccuracy|accuracy|hammingLoss|precision|recall|f1Measure|" 

"precisionByLabel|recallByLabel|f1MeasureByLabel|microPrecision|" 

"microRecall|microF1Measure)", 

typeConverter=TypeConverters.toString) 

metricLabel = Param(Params._dummy(), "metricLabel", 

"The class whose metric will be computed in precisionByLabel|" 

"recallByLabel|f1MeasureByLabel. " 

"Must be >= 0. The default value is 0.", 

typeConverter=TypeConverters.toFloat) 

 

@keyword_only 

def __init__(self, *, predictionCol="prediction", labelCol="label", 

metricName="f1Measure", metricLabel=0.0): 

""" 

__init__(self, \\*, predictionCol="prediction", labelCol="label", \ 

metricName="f1Measure", metricLabel=0.0) 

""" 

super(MultilabelClassificationEvaluator, self).__init__() 

self._java_obj = self._new_java_obj( 

"org.apache.spark.ml.evaluation.MultilabelClassificationEvaluator", self.uid) 

self._setDefault(metricName="f1Measure", metricLabel=0.0) 

kwargs = self._input_kwargs 

self._set(**kwargs) 

 

@since("3.0.0") 

def setMetricName(self, value): 

""" 

Sets the value of :py:attr:`metricName`. 

""" 

return self._set(metricName=value) 

 

@since("3.0.0") 

def getMetricName(self): 

""" 

Gets the value of metricName or its default value. 

""" 

return self.getOrDefault(self.metricName) 

 

@since("3.0.0") 

def setMetricLabel(self, value): 

""" 

Sets the value of :py:attr:`metricLabel`. 

""" 

return self._set(metricLabel=value) 

 

@since("3.0.0") 

def getMetricLabel(self): 

""" 

Gets the value of metricLabel or its default value. 

""" 

return self.getOrDefault(self.metricLabel) 

 

@since("3.0.0") 

def setLabelCol(self, value): 

""" 

Sets the value of :py:attr:`labelCol`. 

""" 

return self._set(labelCol=value) 

 

@since("3.0.0") 

def setPredictionCol(self, value): 

""" 

Sets the value of :py:attr:`predictionCol`. 

""" 

return self._set(predictionCol=value) 

 

@keyword_only 

@since("3.0.0") 

def setParams(self, *, predictionCol="prediction", labelCol="label", 

metricName="f1Measure", metricLabel=0.0): 

""" 

setParams(self, \\*, predictionCol="prediction", labelCol="label", \ 

metricName="f1Measure", metricLabel=0.0) 

Sets params for multilabel classification evaluator. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

 

@inherit_doc 

class ClusteringEvaluator(JavaEvaluator, HasPredictionCol, HasFeaturesCol, HasWeightCol, 

JavaMLReadable, JavaMLWritable): 

""" 

Evaluator for Clustering results, which expects two input 

columns: prediction and features. The metric computes the Silhouette 

measure using the squared Euclidean distance. 

 

The Silhouette is a measure for the validation of the consistency 

within clusters. It ranges between 1 and -1, where a value close to 

1 means that the points in a cluster are close to the other points 

in the same cluster and far from the points of the other clusters. 

 

.. versionadded:: 2.3.0 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

>>> featureAndPredictions = map(lambda x: (Vectors.dense(x[0]), x[1]), 

... [([0.0, 0.5], 0.0), ([0.5, 0.0], 0.0), ([10.0, 11.0], 1.0), 

... ([10.5, 11.5], 1.0), ([1.0, 1.0], 0.0), ([8.0, 6.0], 1.0)]) 

>>> dataset = spark.createDataFrame(featureAndPredictions, ["features", "prediction"]) 

... 

>>> evaluator = ClusteringEvaluator() 

>>> evaluator.setPredictionCol("prediction") 

ClusteringEvaluator... 

>>> evaluator.evaluate(dataset) 

0.9079... 

>>> featureAndPredictionsWithWeight = map(lambda x: (Vectors.dense(x[0]), x[1], x[2]), 

... [([0.0, 0.5], 0.0, 2.5), ([0.5, 0.0], 0.0, 2.5), ([10.0, 11.0], 1.0, 2.5), 

... ([10.5, 11.5], 1.0, 2.5), ([1.0, 1.0], 0.0, 2.5), ([8.0, 6.0], 1.0, 2.5)]) 

>>> dataset = spark.createDataFrame( 

... featureAndPredictionsWithWeight, ["features", "prediction", "weight"]) 

>>> evaluator = ClusteringEvaluator() 

>>> evaluator.setPredictionCol("prediction") 

ClusteringEvaluator... 

>>> evaluator.setWeightCol("weight") 

ClusteringEvaluator... 

>>> evaluator.evaluate(dataset) 

0.9079... 

>>> ce_path = temp_path + "/ce" 

>>> evaluator.save(ce_path) 

>>> evaluator2 = ClusteringEvaluator.load(ce_path) 

>>> str(evaluator2.getPredictionCol()) 

'prediction' 

""" 

metricName = Param(Params._dummy(), "metricName", 

"metric name in evaluation (silhouette)", 

typeConverter=TypeConverters.toString) 

distanceMeasure = Param(Params._dummy(), "distanceMeasure", "The distance measure. " + 

"Supported options: 'squaredEuclidean' and 'cosine'.", 

typeConverter=TypeConverters.toString) 

 

@keyword_only 

def __init__(self, *, predictionCol="prediction", featuresCol="features", 

metricName="silhouette", distanceMeasure="squaredEuclidean", weightCol=None): 

""" 

__init__(self, \\*, predictionCol="prediction", featuresCol="features", \ 

metricName="silhouette", distanceMeasure="squaredEuclidean", weightCol=None) 

""" 

super(ClusteringEvaluator, self).__init__() 

self._java_obj = self._new_java_obj( 

"org.apache.spark.ml.evaluation.ClusteringEvaluator", self.uid) 

self._setDefault(metricName="silhouette", distanceMeasure="squaredEuclidean") 

kwargs = self._input_kwargs 

self._set(**kwargs) 

 

@keyword_only 

@since("2.3.0") 

def setParams(self, *, predictionCol="prediction", featuresCol="features", 

metricName="silhouette", distanceMeasure="squaredEuclidean", weightCol=None): 

""" 

setParams(self, \\*, predictionCol="prediction", featuresCol="features", \ 

metricName="silhouette", distanceMeasure="squaredEuclidean", weightCol=None) 

Sets params for clustering evaluator. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("2.3.0") 

def setMetricName(self, value): 

""" 

Sets the value of :py:attr:`metricName`. 

""" 

return self._set(metricName=value) 

 

@since("2.3.0") 

def getMetricName(self): 

""" 

Gets the value of metricName or its default value. 

""" 

return self.getOrDefault(self.metricName) 

 

@since("2.4.0") 

def setDistanceMeasure(self, value): 

""" 

Sets the value of :py:attr:`distanceMeasure`. 

""" 

return self._set(distanceMeasure=value) 

 

@since("2.4.0") 

def getDistanceMeasure(self): 

""" 

Gets the value of `distanceMeasure` 

""" 

return self.getOrDefault(self.distanceMeasure) 

 

def setFeaturesCol(self, value): 

""" 

Sets the value of :py:attr:`featuresCol`. 

""" 

return self._set(featuresCol=value) 

 

def setPredictionCol(self, value): 

""" 

Sets the value of :py:attr:`predictionCol`. 

""" 

return self._set(predictionCol=value) 

 

@since("3.1.0") 

def setWeightCol(self, value): 

""" 

Sets the value of :py:attr:`weightCol`. 

""" 

return self._set(weightCol=value) 

 

 

@inherit_doc 

class RankingEvaluator(JavaEvaluator, HasLabelCol, HasPredictionCol, 

JavaMLReadable, JavaMLWritable): 

""" 

Evaluator for Ranking, which expects two input 

columns: prediction and label. 

 

.. versionadded:: 3.0.0 

 

Notes 

----- 

Experimental 

 

Examples 

-------- 

>>> scoreAndLabels = [([1.0, 6.0, 2.0, 7.0, 8.0, 3.0, 9.0, 10.0, 4.0, 5.0], 

... [1.0, 2.0, 3.0, 4.0, 5.0]), 

... ([4.0, 1.0, 5.0, 6.0, 2.0, 7.0, 3.0, 8.0, 9.0, 10.0], [1.0, 2.0, 3.0]), 

... ([1.0, 2.0, 3.0, 4.0, 5.0], [])] 

>>> dataset = spark.createDataFrame(scoreAndLabels, ["prediction", "label"]) 

... 

>>> evaluator = RankingEvaluator() 

>>> evaluator.setPredictionCol("prediction") 

RankingEvaluator... 

>>> evaluator.evaluate(dataset) 

0.35... 

>>> evaluator.evaluate(dataset, {evaluator.metricName: "precisionAtK", evaluator.k: 2}) 

0.33... 

>>> ranke_path = temp_path + "/ranke" 

>>> evaluator.save(ranke_path) 

>>> evaluator2 = RankingEvaluator.load(ranke_path) 

>>> str(evaluator2.getPredictionCol()) 

'prediction' 

""" 

metricName = Param(Params._dummy(), "metricName", 

"metric name in evaluation " 

"(meanAveragePrecision|meanAveragePrecisionAtK|" 

"precisionAtK|ndcgAtK|recallAtK)", 

typeConverter=TypeConverters.toString) 

k = Param(Params._dummy(), "k", 

"The ranking position value used in meanAveragePrecisionAtK|precisionAtK|" 

"ndcgAtK|recallAtK. Must be > 0. The default value is 10.", 

typeConverter=TypeConverters.toInt) 

 

@keyword_only 

def __init__(self, *, predictionCol="prediction", labelCol="label", 

metricName="meanAveragePrecision", k=10): 

""" 

__init__(self, \\*, predictionCol="prediction", labelCol="label", \ 

metricName="meanAveragePrecision", k=10) 

""" 

super(RankingEvaluator, self).__init__() 

self._java_obj = self._new_java_obj( 

"org.apache.spark.ml.evaluation.RankingEvaluator", self.uid) 

self._setDefault(metricName="meanAveragePrecision", k=10) 

kwargs = self._input_kwargs 

self._set(**kwargs) 

 

@since("3.0.0") 

def setMetricName(self, value): 

""" 

Sets the value of :py:attr:`metricName`. 

""" 

return self._set(metricName=value) 

 

@since("3.0.0") 

def getMetricName(self): 

""" 

Gets the value of metricName or its default value. 

""" 

return self.getOrDefault(self.metricName) 

 

@since("3.0.0") 

def setK(self, value): 

""" 

Sets the value of :py:attr:`k`. 

""" 

return self._set(k=value) 

 

@since("3.0.0") 

def getK(self): 

""" 

Gets the value of k or its default value. 

""" 

return self.getOrDefault(self.k) 

 

@since("3.0.0") 

def setLabelCol(self, value): 

""" 

Sets the value of :py:attr:`labelCol`. 

""" 

return self._set(labelCol=value) 

 

@since("3.0.0") 

def setPredictionCol(self, value): 

""" 

Sets the value of :py:attr:`predictionCol`. 

""" 

return self._set(predictionCol=value) 

 

@keyword_only 

@since("3.0.0") 

def setParams(self, *, predictionCol="prediction", labelCol="label", 

metricName="meanAveragePrecision", k=10): 

""" 

setParams(self, \\*, predictionCol="prediction", labelCol="label", \ 

metricName="meanAveragePrecision", k=10) 

Sets params for ranking evaluator. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

 

if __name__ == "__main__": 

import doctest 

import tempfile 

import pyspark.ml.evaluation 

from pyspark.sql import SparkSession 

globs = pyspark.ml.evaluation.__dict__.copy() 

# The small batch size here ensures that we see multiple batches, 

# even in these small test examples: 

spark = SparkSession.builder\ 

.master("local[2]")\ 

.appName("ml.evaluation tests")\ 

.getOrCreate() 

globs['spark'] = spark 

temp_path = tempfile.mkdtemp() 

globs['temp_path'] = temp_path 

try: 

(failure_count, test_count) = doctest.testmod(globs=globs, optionflags=doctest.ELLIPSIS) 

spark.stop() 

finally: 

from shutil import rmtree 

try: 

rmtree(temp_path) 

except OSError: 

pass 

948 ↛ 949line 948 didn't jump to line 949, because the condition on line 948 was never true if failure_count: 

sys.exit(-1)