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

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

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

# 

# 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 

import warnings 

 

from pyspark import since, keyword_only 

from pyspark.ml.param.shared import HasMaxIter, HasFeaturesCol, HasSeed, HasPredictionCol, \ 

HasAggregationDepth, HasWeightCol, HasTol, HasProbabilityCol, HasDistanceMeasure, \ 

HasCheckpointInterval, Param, Params, TypeConverters 

from pyspark.ml.util import JavaMLWritable, JavaMLReadable, GeneralJavaMLWritable, \ 

HasTrainingSummary, SparkContext 

from pyspark.ml.wrapper import JavaEstimator, JavaModel, JavaParams, JavaWrapper 

from pyspark.ml.common import inherit_doc, _java2py 

from pyspark.ml.stat import MultivariateGaussian 

from pyspark.sql import DataFrame 

 

__all__ = ['BisectingKMeans', 'BisectingKMeansModel', 'BisectingKMeansSummary', 

'KMeans', 'KMeansModel', 'KMeansSummary', 

'GaussianMixture', 'GaussianMixtureModel', 'GaussianMixtureSummary', 

'LDA', 'LDAModel', 'LocalLDAModel', 'DistributedLDAModel', 'PowerIterationClustering'] 

 

 

class ClusteringSummary(JavaWrapper): 

""" 

Clustering results for a given model. 

 

.. versionadded:: 2.1.0 

""" 

 

@property 

@since("2.1.0") 

def predictionCol(self): 

""" 

Name for column of predicted clusters in `predictions`. 

""" 

return self._call_java("predictionCol") 

 

@property 

@since("2.1.0") 

def predictions(self): 

""" 

DataFrame produced by the model's `transform` method. 

""" 

return self._call_java("predictions") 

 

@property 

@since("2.1.0") 

def featuresCol(self): 

""" 

Name for column of features in `predictions`. 

""" 

return self._call_java("featuresCol") 

 

@property 

@since("2.1.0") 

def k(self): 

""" 

The number of clusters the model was trained with. 

""" 

return self._call_java("k") 

 

@property 

@since("2.1.0") 

def cluster(self): 

""" 

DataFrame of predicted cluster centers for each training data point. 

""" 

return self._call_java("cluster") 

 

@property 

@since("2.1.0") 

def clusterSizes(self): 

""" 

Size of (number of data points in) each cluster. 

""" 

return self._call_java("clusterSizes") 

 

@property 

@since("2.4.0") 

def numIter(self): 

""" 

Number of iterations. 

""" 

return self._call_java("numIter") 

 

 

@inherit_doc 

class _GaussianMixtureParams(HasMaxIter, HasFeaturesCol, HasSeed, HasPredictionCol, 

HasProbabilityCol, HasTol, HasAggregationDepth, HasWeightCol): 

""" 

Params for :py:class:`GaussianMixture` and :py:class:`GaussianMixtureModel`. 

 

.. versionadded:: 3.0.0 

""" 

 

k = Param(Params._dummy(), "k", "Number of independent Gaussians in the mixture model. " + 

"Must be > 1.", typeConverter=TypeConverters.toInt) 

 

def __init__(self, *args): 

super(_GaussianMixtureParams, self).__init__(*args) 

self._setDefault(k=2, tol=0.01, maxIter=100, aggregationDepth=2) 

 

@since("2.0.0") 

def getK(self): 

""" 

Gets the value of `k` 

""" 

return self.getOrDefault(self.k) 

 

 

class GaussianMixtureModel(JavaModel, _GaussianMixtureParams, JavaMLWritable, JavaMLReadable, 

HasTrainingSummary): 

""" 

Model fitted by GaussianMixture. 

 

.. versionadded:: 2.0.0 

""" 

 

@since("3.0.0") 

def setFeaturesCol(self, value): 

""" 

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

""" 

return self._set(featuresCol=value) 

 

@since("3.0.0") 

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) 

 

@property 

@since("2.0.0") 

def weights(self): 

""" 

Weight for each Gaussian distribution in the mixture. 

This is a multinomial probability distribution over the k Gaussians, 

where weights[i] is the weight for Gaussian i, and weights sum to 1. 

""" 

return self._call_java("weights") 

 

@property 

@since("3.0.0") 

def gaussians(self): 

""" 

Array of :py:class:`MultivariateGaussian` where gaussians[i] represents 

the Multivariate Gaussian (Normal) Distribution for Gaussian i 

""" 

sc = SparkContext._active_spark_context 

jgaussians = self._java_obj.gaussians() 

return [ 

MultivariateGaussian(_java2py(sc, jgaussian.mean()), _java2py(sc, jgaussian.cov())) 

for jgaussian in jgaussians] 

 

@property 

@since("2.0.0") 

def gaussiansDF(self): 

""" 

Retrieve Gaussian distributions as a DataFrame. 

Each row represents a Gaussian Distribution. 

The DataFrame has two columns: mean (Vector) and cov (Matrix). 

""" 

return self._call_java("gaussiansDF") 

 

@property 

@since("2.1.0") 

def summary(self): 

""" 

Gets summary (cluster assignments, cluster sizes) of the model trained on the 

training set. An exception is thrown if no summary exists. 

""" 

195 ↛ 198line 195 didn't jump to line 198, because the condition on line 195 was never false if self.hasSummary: 

return GaussianMixtureSummary(super(GaussianMixtureModel, self).summary) 

else: 

raise RuntimeError("No training summary available for this %s" % 

self.__class__.__name__) 

 

@since("3.0.0") 

def predict(self, value): 

""" 

Predict label for the given features. 

""" 

return self._call_java("predict", value) 

 

@since("3.0.0") 

def predictProbability(self, value): 

""" 

Predict probability for the given features. 

""" 

return self._call_java("predictProbability", value) 

 

 

@inherit_doc 

class GaussianMixture(JavaEstimator, _GaussianMixtureParams, JavaMLWritable, JavaMLReadable): 

""" 

GaussianMixture clustering. 

This class performs expectation maximization for multivariate Gaussian 

Mixture Models (GMMs). A GMM represents a composite distribution of 

independent Gaussian distributions with associated "mixing" weights 

specifying each's contribution to the composite. 

 

Given a set of sample points, this class will maximize the log-likelihood 

for a mixture of k Gaussians, iterating until the log-likelihood changes by 

less than convergenceTol, or until it has reached the max number of iterations. 

While this process is generally guaranteed to converge, it is not guaranteed 

to find a global optimum. 

 

.. versionadded:: 2.0.0 

 

Notes 

----- 

For high-dimensional data (with many features), this algorithm may perform poorly. 

This is due to high-dimensional data (a) making it difficult to cluster at all 

(based on statistical/theoretical arguments) and (b) numerical issues with 

Gaussian distributions. 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

 

>>> data = [(Vectors.dense([-0.1, -0.05 ]),), 

... (Vectors.dense([-0.01, -0.1]),), 

... (Vectors.dense([0.9, 0.8]),), 

... (Vectors.dense([0.75, 0.935]),), 

... (Vectors.dense([-0.83, -0.68]),), 

... (Vectors.dense([-0.91, -0.76]),)] 

>>> df = spark.createDataFrame(data, ["features"]) 

>>> gm = GaussianMixture(k=3, tol=0.0001, seed=10) 

>>> gm.getMaxIter() 

100 

>>> gm.setMaxIter(30) 

GaussianMixture... 

>>> gm.getMaxIter() 

30 

>>> model = gm.fit(df) 

>>> model.getAggregationDepth() 

2 

>>> model.getFeaturesCol() 

'features' 

>>> model.setPredictionCol("newPrediction") 

GaussianMixtureModel... 

>>> model.predict(df.head().features) 

2 

>>> model.predictProbability(df.head().features) 

DenseVector([0.0, 0.0, 1.0]) 

>>> model.hasSummary 

True 

>>> summary = model.summary 

>>> summary.k 

3 

>>> summary.clusterSizes 

[2, 2, 2] 

>>> weights = model.weights 

>>> len(weights) 

3 

>>> gaussians = model.gaussians 

>>> len(gaussians) 

3 

>>> gaussians[0].mean 

DenseVector([0.825, 0.8675]) 

>>> gaussians[0].cov 

DenseMatrix(2, 2, [0.0056, -0.0051, -0.0051, 0.0046], 0) 

>>> gaussians[1].mean 

DenseVector([-0.87, -0.72]) 

>>> gaussians[1].cov 

DenseMatrix(2, 2, [0.0016, 0.0016, 0.0016, 0.0016], 0) 

>>> gaussians[2].mean 

DenseVector([-0.055, -0.075]) 

>>> gaussians[2].cov 

DenseMatrix(2, 2, [0.002, -0.0011, -0.0011, 0.0006], 0) 

>>> model.gaussiansDF.select("mean").head() 

Row(mean=DenseVector([0.825, 0.8675])) 

>>> model.gaussiansDF.select("cov").head() 

Row(cov=DenseMatrix(2, 2, [0.0056, -0.0051, -0.0051, 0.0046], False)) 

>>> transformed = model.transform(df).select("features", "newPrediction") 

>>> rows = transformed.collect() 

>>> rows[4].newPrediction == rows[5].newPrediction 

True 

>>> rows[2].newPrediction == rows[3].newPrediction 

True 

>>> gmm_path = temp_path + "/gmm" 

>>> gm.save(gmm_path) 

>>> gm2 = GaussianMixture.load(gmm_path) 

>>> gm2.getK() 

3 

>>> model_path = temp_path + "/gmm_model" 

>>> model.save(model_path) 

>>> model2 = GaussianMixtureModel.load(model_path) 

>>> model2.hasSummary 

False 

>>> model2.weights == model.weights 

True 

>>> model2.gaussians[0].mean == model.gaussians[0].mean 

True 

>>> model2.gaussians[0].cov == model.gaussians[0].cov 

True 

>>> model2.gaussians[1].mean == model.gaussians[1].mean 

True 

>>> model2.gaussians[1].cov == model.gaussians[1].cov 

True 

>>> model2.gaussians[2].mean == model.gaussians[2].mean 

True 

>>> model2.gaussians[2].cov == model.gaussians[2].cov 

True 

>>> model2.gaussiansDF.select("mean").head() 

Row(mean=DenseVector([0.825, 0.8675])) 

>>> model2.gaussiansDF.select("cov").head() 

Row(cov=DenseMatrix(2, 2, [0.0056, -0.0051, -0.0051, 0.0046], False)) 

>>> model.transform(df).take(1) == model2.transform(df).take(1) 

True 

>>> gm2.setWeightCol("weight") 

GaussianMixture... 

""" 

 

@keyword_only 

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

probabilityCol="probability", tol=0.01, maxIter=100, seed=None, 

aggregationDepth=2, weightCol=None): 

""" 

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

probabilityCol="probability", tol=0.01, maxIter=100, seed=None, \ 

aggregationDepth=2, weightCol=None) 

""" 

super(GaussianMixture, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.clustering.GaussianMixture", 

self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

def _create_model(self, java_model): 

return GaussianMixtureModel(java_model) 

 

@keyword_only 

@since("2.0.0") 

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

probabilityCol="probability", tol=0.01, maxIter=100, seed=None, 

aggregationDepth=2, weightCol=None): 

""" 

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

probabilityCol="probability", tol=0.01, maxIter=100, seed=None, \ 

aggregationDepth=2, weightCol=None) 

 

Sets params for GaussianMixture. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("2.0.0") 

def setK(self, value): 

""" 

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

""" 

return self._set(k=value) 

 

@since("2.0.0") 

def setMaxIter(self, value): 

""" 

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

""" 

return self._set(maxIter=value) 

 

@since("2.0.0") 

def setFeaturesCol(self, value): 

""" 

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

""" 

return self._set(featuresCol=value) 

 

@since("2.0.0") 

def setPredictionCol(self, value): 

""" 

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

""" 

return self._set(predictionCol=value) 

 

@since("2.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) 

 

@since("2.0.0") 

def setSeed(self, value): 

""" 

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

""" 

return self._set(seed=value) 

 

@since("2.0.0") 

def setTol(self, value): 

""" 

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

""" 

return self._set(tol=value) 

 

@since("3.0.0") 

def setAggregationDepth(self, value): 

""" 

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

""" 

return self._set(aggregationDepth=value) 

 

 

class GaussianMixtureSummary(ClusteringSummary): 

""" 

Gaussian mixture clustering results for a given model. 

 

.. versionadded:: 2.1.0 

""" 

 

@property 

@since("2.1.0") 

def probabilityCol(self): 

""" 

Name for column of predicted probability of each cluster in `predictions`. 

""" 

return self._call_java("probabilityCol") 

 

@property 

@since("2.1.0") 

def probability(self): 

""" 

DataFrame of probabilities of each cluster for each training data point. 

""" 

return self._call_java("probability") 

 

@property 

@since("2.2.0") 

def logLikelihood(self): 

""" 

Total log-likelihood for this model on the given data. 

""" 

return self._call_java("logLikelihood") 

 

 

class KMeansSummary(ClusteringSummary): 

""" 

Summary of KMeans. 

 

.. versionadded:: 2.1.0 

""" 

 

@property 

@since("2.4.0") 

def trainingCost(self): 

""" 

K-means cost (sum of squared distances to the nearest centroid for all points in the 

training dataset). This is equivalent to sklearn's inertia. 

""" 

return self._call_java("trainingCost") 

 

 

@inherit_doc 

class _KMeansParams(HasMaxIter, HasFeaturesCol, HasSeed, HasPredictionCol, HasTol, 

HasDistanceMeasure, HasWeightCol): 

""" 

Params for :py:class:`KMeans` and :py:class:`KMeansModel`. 

 

.. versionadded:: 3.0.0 

""" 

 

k = Param(Params._dummy(), "k", "The number of clusters to create. Must be > 1.", 

typeConverter=TypeConverters.toInt) 

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

"The initialization algorithm. This can be either \"random\" to " + 

"choose random points as initial cluster centers, or \"k-means||\" " + 

"to use a parallel variant of k-means++", 

typeConverter=TypeConverters.toString) 

initSteps = Param(Params._dummy(), "initSteps", "The number of steps for k-means|| " + 

"initialization mode. Must be > 0.", typeConverter=TypeConverters.toInt) 

 

def __init__(self, *args): 

super(_KMeansParams, self).__init__(*args) 

self._setDefault(k=2, initMode="k-means||", initSteps=2, tol=1e-4, maxIter=20, 

distanceMeasure="euclidean") 

 

@since("1.5.0") 

def getK(self): 

""" 

Gets the value of `k` 

""" 

return self.getOrDefault(self.k) 

 

@since("1.5.0") 

def getInitMode(self): 

""" 

Gets the value of `initMode` 

""" 

return self.getOrDefault(self.initMode) 

 

@since("1.5.0") 

def getInitSteps(self): 

""" 

Gets the value of `initSteps` 

""" 

return self.getOrDefault(self.initSteps) 

 

 

class KMeansModel(JavaModel, _KMeansParams, GeneralJavaMLWritable, JavaMLReadable, 

HasTrainingSummary): 

""" 

Model fitted by KMeans. 

 

.. versionadded:: 1.5.0 

""" 

 

@since("3.0.0") 

def setFeaturesCol(self, value): 

""" 

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

""" 

return self._set(featuresCol=value) 

 

@since("3.0.0") 

def setPredictionCol(self, value): 

""" 

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

""" 

return self._set(predictionCol=value) 

 

@since("1.5.0") 

def clusterCenters(self): 

"""Get the cluster centers, represented as a list of NumPy arrays.""" 

return [c.toArray() for c in self._call_java("clusterCenters")] 

 

@property 

@since("2.1.0") 

def summary(self): 

""" 

Gets summary (cluster assignments, cluster sizes) of the model trained on the 

training set. An exception is thrown if no summary exists. 

""" 

564 ↛ 567line 564 didn't jump to line 567, because the condition on line 564 was never false if self.hasSummary: 

return KMeansSummary(super(KMeansModel, self).summary) 

else: 

raise RuntimeError("No training summary available for this %s" % 

self.__class__.__name__) 

 

@since("3.0.0") 

def predict(self, value): 

""" 

Predict label for the given features. 

""" 

return self._call_java("predict", value) 

 

 

@inherit_doc 

class KMeans(JavaEstimator, _KMeansParams, JavaMLWritable, JavaMLReadable): 

""" 

K-means clustering with a k-means++ like initialization mode 

(the k-means|| algorithm by Bahmani et al). 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

>>> data = [(Vectors.dense([0.0, 0.0]), 2.0), (Vectors.dense([1.0, 1.0]), 2.0), 

... (Vectors.dense([9.0, 8.0]), 2.0), (Vectors.dense([8.0, 9.0]), 2.0)] 

>>> df = spark.createDataFrame(data, ["features", "weighCol"]) 

>>> kmeans = KMeans(k=2) 

>>> kmeans.setSeed(1) 

KMeans... 

>>> kmeans.setWeightCol("weighCol") 

KMeans... 

>>> kmeans.setMaxIter(10) 

KMeans... 

>>> kmeans.getMaxIter() 

10 

>>> kmeans.clear(kmeans.maxIter) 

>>> model = kmeans.fit(df) 

>>> model.getDistanceMeasure() 

'euclidean' 

>>> model.setPredictionCol("newPrediction") 

KMeansModel... 

>>> model.predict(df.head().features) 

0 

>>> centers = model.clusterCenters() 

>>> len(centers) 

2 

>>> transformed = model.transform(df).select("features", "newPrediction") 

>>> rows = transformed.collect() 

>>> rows[0].newPrediction == rows[1].newPrediction 

True 

>>> rows[2].newPrediction == rows[3].newPrediction 

True 

>>> model.hasSummary 

True 

>>> summary = model.summary 

>>> summary.k 

2 

>>> summary.clusterSizes 

[2, 2] 

>>> summary.trainingCost 

4.0 

>>> kmeans_path = temp_path + "/kmeans" 

>>> kmeans.save(kmeans_path) 

>>> kmeans2 = KMeans.load(kmeans_path) 

>>> kmeans2.getK() 

2 

>>> model_path = temp_path + "/kmeans_model" 

>>> model.save(model_path) 

>>> model2 = KMeansModel.load(model_path) 

>>> model2.hasSummary 

False 

>>> model.clusterCenters()[0] == model2.clusterCenters()[0] 

array([ True, True], dtype=bool) 

>>> model.clusterCenters()[1] == model2.clusterCenters()[1] 

array([ True, True], dtype=bool) 

>>> model.transform(df).take(1) == model2.transform(df).take(1) 

True 

""" 

 

@keyword_only 

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

initMode="k-means||", initSteps=2, tol=1e-4, maxIter=20, seed=None, 

distanceMeasure="euclidean", weightCol=None): 

""" 

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

initMode="k-means||", initSteps=2, tol=1e-4, maxIter=20, seed=None, \ 

distanceMeasure="euclidean", weightCol=None) 

""" 

super(KMeans, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.clustering.KMeans", self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

def _create_model(self, java_model): 

return KMeansModel(java_model) 

 

@keyword_only 

@since("1.5.0") 

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

initMode="k-means||", initSteps=2, tol=1e-4, maxIter=20, seed=None, 

distanceMeasure="euclidean", weightCol=None): 

""" 

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

initMode="k-means||", initSteps=2, tol=1e-4, maxIter=20, seed=None, \ 

distanceMeasure="euclidean", weightCol=None) 

 

Sets params for KMeans. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("1.5.0") 

def setK(self, value): 

""" 

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

""" 

return self._set(k=value) 

 

@since("1.5.0") 

def setInitMode(self, value): 

""" 

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

""" 

return self._set(initMode=value) 

 

@since("1.5.0") 

def setInitSteps(self, value): 

""" 

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

""" 

return self._set(initSteps=value) 

 

@since("2.4.0") 

def setDistanceMeasure(self, value): 

""" 

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

""" 

return self._set(distanceMeasure=value) 

 

@since("1.5.0") 

def setMaxIter(self, value): 

""" 

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

""" 

return self._set(maxIter=value) 

 

@since("1.5.0") 

def setFeaturesCol(self, value): 

""" 

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

""" 

return self._set(featuresCol=value) 

 

@since("1.5.0") 

def setPredictionCol(self, value): 

""" 

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

""" 

return self._set(predictionCol=value) 

 

@since("1.5.0") 

def setSeed(self, value): 

""" 

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

""" 

return self._set(seed=value) 

 

@since("1.5.0") 

def setTol(self, value): 

""" 

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

""" 

return self._set(tol=value) 

 

@since("3.0.0") 

def setWeightCol(self, value): 

""" 

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

""" 

return self._set(weightCol=value) 

 

 

@inherit_doc 

class _BisectingKMeansParams(HasMaxIter, HasFeaturesCol, HasSeed, HasPredictionCol, 

HasDistanceMeasure, HasWeightCol): 

""" 

Params for :py:class:`BisectingKMeans` and :py:class:`BisectingKMeansModel`. 

 

.. versionadded:: 3.0.0 

""" 

 

k = Param(Params._dummy(), "k", "The desired number of leaf clusters. Must be > 1.", 

typeConverter=TypeConverters.toInt) 

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

"The minimum number of points (if >= 1.0) or the minimum " + 

"proportion of points (if < 1.0) of a divisible cluster.", 

typeConverter=TypeConverters.toFloat) 

 

def __init__(self, *args): 

super(_BisectingKMeansParams, self).__init__(*args) 

self._setDefault(maxIter=20, k=4, minDivisibleClusterSize=1.0) 

 

@since("2.0.0") 

def getK(self): 

""" 

Gets the value of `k` or its default value. 

""" 

return self.getOrDefault(self.k) 

 

@since("2.0.0") 

def getMinDivisibleClusterSize(self): 

""" 

Gets the value of `minDivisibleClusterSize` or its default value. 

""" 

return self.getOrDefault(self.minDivisibleClusterSize) 

 

 

class BisectingKMeansModel(JavaModel, _BisectingKMeansParams, JavaMLWritable, JavaMLReadable, 

HasTrainingSummary): 

""" 

Model fitted by BisectingKMeans. 

 

.. versionadded:: 2.0.0 

""" 

 

@since("3.0.0") 

def setFeaturesCol(self, value): 

""" 

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

""" 

return self._set(featuresCol=value) 

 

@since("3.0.0") 

def setPredictionCol(self, value): 

""" 

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

""" 

return self._set(predictionCol=value) 

 

@since("2.0.0") 

def clusterCenters(self): 

"""Get the cluster centers, represented as a list of NumPy arrays.""" 

return [c.toArray() for c in self._call_java("clusterCenters")] 

 

@since("2.0.0") 

def computeCost(self, dataset): 

""" 

Computes the sum of squared distances between the input points 

and their corresponding cluster centers. 

 

.. deprecated:: 3.0.0 

It will be removed in future versions. Use :py:class:`ClusteringEvaluator` instead. 

You can also get the cost on the training dataset in the summary. 

""" 

warnings.warn("Deprecated in 3.0.0. It will be removed in future versions. Use " 

"ClusteringEvaluator instead. You can also get the cost on the training " 

"dataset in the summary.", FutureWarning) 

return self._call_java("computeCost", dataset) 

 

@property 

@since("2.1.0") 

def summary(self): 

""" 

Gets summary (cluster assignments, cluster sizes) of the model trained on the 

training set. An exception is thrown if no summary exists. 

""" 

832 ↛ 835line 832 didn't jump to line 835, because the condition on line 832 was never false if self.hasSummary: 

return BisectingKMeansSummary(super(BisectingKMeansModel, self).summary) 

else: 

raise RuntimeError("No training summary available for this %s" % 

self.__class__.__name__) 

 

@since("3.0.0") 

def predict(self, value): 

""" 

Predict label for the given features. 

""" 

return self._call_java("predict", value) 

 

 

@inherit_doc 

class BisectingKMeans(JavaEstimator, _BisectingKMeansParams, JavaMLWritable, JavaMLReadable): 

""" 

A bisecting k-means algorithm based on the paper "A comparison of document clustering 

techniques" by Steinbach, Karypis, and Kumar, with modification to fit Spark. 

The algorithm starts from a single cluster that contains all points. 

Iteratively it finds divisible clusters on the bottom level and bisects each of them using 

k-means, until there are `k` leaf clusters in total or no leaf clusters are divisible. 

The bisecting steps of clusters on the same level are grouped together to increase parallelism. 

If bisecting all divisible clusters on the bottom level would result more than `k` leaf 

clusters, larger clusters get higher priority. 

 

.. versionadded:: 2.0.0 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

>>> data = [(Vectors.dense([0.0, 0.0]), 2.0), (Vectors.dense([1.0, 1.0]), 2.0), 

... (Vectors.dense([9.0, 8.0]), 2.0), (Vectors.dense([8.0, 9.0]), 2.0)] 

>>> df = spark.createDataFrame(data, ["features", "weighCol"]) 

>>> bkm = BisectingKMeans(k=2, minDivisibleClusterSize=1.0) 

>>> bkm.setMaxIter(10) 

BisectingKMeans... 

>>> bkm.getMaxIter() 

10 

>>> bkm.clear(bkm.maxIter) 

>>> bkm.setSeed(1) 

BisectingKMeans... 

>>> bkm.setWeightCol("weighCol") 

BisectingKMeans... 

>>> bkm.getSeed() 

1 

>>> bkm.clear(bkm.seed) 

>>> model = bkm.fit(df) 

>>> model.getMaxIter() 

20 

>>> model.setPredictionCol("newPrediction") 

BisectingKMeansModel... 

>>> model.predict(df.head().features) 

0 

>>> centers = model.clusterCenters() 

>>> len(centers) 

2 

>>> model.computeCost(df) 

2.0 

>>> model.hasSummary 

True 

>>> summary = model.summary 

>>> summary.k 

2 

>>> summary.clusterSizes 

[2, 2] 

>>> summary.trainingCost 

4.000... 

>>> transformed = model.transform(df).select("features", "newPrediction") 

>>> rows = transformed.collect() 

>>> rows[0].newPrediction == rows[1].newPrediction 

True 

>>> rows[2].newPrediction == rows[3].newPrediction 

True 

>>> bkm_path = temp_path + "/bkm" 

>>> bkm.save(bkm_path) 

>>> bkm2 = BisectingKMeans.load(bkm_path) 

>>> bkm2.getK() 

2 

>>> bkm2.getDistanceMeasure() 

'euclidean' 

>>> model_path = temp_path + "/bkm_model" 

>>> model.save(model_path) 

>>> model2 = BisectingKMeansModel.load(model_path) 

>>> model2.hasSummary 

False 

>>> model.clusterCenters()[0] == model2.clusterCenters()[0] 

array([ True, True], dtype=bool) 

>>> model.clusterCenters()[1] == model2.clusterCenters()[1] 

array([ True, True], dtype=bool) 

>>> model.transform(df).take(1) == model2.transform(df).take(1) 

True 

""" 

 

@keyword_only 

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

seed=None, k=4, minDivisibleClusterSize=1.0, distanceMeasure="euclidean", 

weightCol=None): 

""" 

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

seed=None, k=4, minDivisibleClusterSize=1.0, distanceMeasure="euclidean", \ 

weightCol=None) 

""" 

super(BisectingKMeans, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.clustering.BisectingKMeans", 

self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("2.0.0") 

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

seed=None, k=4, minDivisibleClusterSize=1.0, distanceMeasure="euclidean", 

weightCol=None): 

""" 

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

seed=None, k=4, minDivisibleClusterSize=1.0, distanceMeasure="euclidean", \ 

weightCol=None) 

Sets params for BisectingKMeans. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("2.0.0") 

def setK(self, value): 

""" 

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

""" 

return self._set(k=value) 

 

@since("2.0.0") 

def setMinDivisibleClusterSize(self, value): 

""" 

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

""" 

return self._set(minDivisibleClusterSize=value) 

 

@since("2.4.0") 

def setDistanceMeasure(self, value): 

""" 

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

""" 

return self._set(distanceMeasure=value) 

 

@since("2.0.0") 

def setMaxIter(self, value): 

""" 

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

""" 

return self._set(maxIter=value) 

 

@since("2.0.0") 

def setFeaturesCol(self, value): 

""" 

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

""" 

return self._set(featuresCol=value) 

 

@since("2.0.0") 

def setPredictionCol(self, value): 

""" 

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

""" 

return self._set(predictionCol=value) 

 

@since("2.0.0") 

def setSeed(self, value): 

""" 

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

""" 

return self._set(seed=value) 

 

@since("3.0.0") 

def setWeightCol(self, value): 

""" 

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

""" 

return self._set(weightCol=value) 

 

def _create_model(self, java_model): 

return BisectingKMeansModel(java_model) 

 

 

class BisectingKMeansSummary(ClusteringSummary): 

""" 

Bisecting KMeans clustering results for a given model. 

 

.. versionadded:: 2.1.0 

""" 

 

@property 

@since("3.0.0") 

def trainingCost(self): 

""" 

Sum of squared distances to the nearest centroid for all points in the training dataset. 

This is equivalent to sklearn's inertia. 

""" 

return self._call_java("trainingCost") 

 

 

@inherit_doc 

class _LDAParams(HasMaxIter, HasFeaturesCol, HasSeed, HasCheckpointInterval): 

""" 

Params for :py:class:`LDA` and :py:class:`LDAModel`. 

 

.. versionadded:: 3.0.0 

""" 

 

k = Param(Params._dummy(), "k", "The number of topics (clusters) to infer. Must be > 1.", 

typeConverter=TypeConverters.toInt) 

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

"Optimizer or inference algorithm used to estimate the LDA model. " 

"Supported: online, em", typeConverter=TypeConverters.toString) 

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

"A (positive) learning parameter that downweights early iterations." 

" Larger values make early iterations count less", 

typeConverter=TypeConverters.toFloat) 

learningDecay = Param(Params._dummy(), "learningDecay", "Learning rate, set as an" 

"exponential decay rate. This should be between (0.5, 1.0] to " 

"guarantee asymptotic convergence.", typeConverter=TypeConverters.toFloat) 

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

"Fraction of the corpus to be sampled and used in each iteration " 

"of mini-batch gradient descent, in range (0, 1].", 

typeConverter=TypeConverters.toFloat) 

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

"Indicates whether the docConcentration (Dirichlet parameter " 

"for document-topic distribution) will be optimized during " 

"training.", typeConverter=TypeConverters.toBoolean) 

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

"Concentration parameter (commonly named \"alpha\") for the " 

"prior placed on documents' distributions over topics (\"theta\").", 

typeConverter=TypeConverters.toListFloat) 

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

"Concentration parameter (commonly named \"beta\" or \"eta\") for " 

"the prior placed on topic' distributions over terms.", 

typeConverter=TypeConverters.toFloat) 

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

"Output column with estimates of the topic mixture distribution " 

"for each document (often called \"theta\" in the literature). " 

"Returns a vector of zeros for an empty document.", 

typeConverter=TypeConverters.toString) 

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

"(For EM optimizer) If using checkpointing, this indicates whether" 

" to keep the last checkpoint. If false, then the checkpoint will be" 

" deleted. Deleting the checkpoint can cause failures if a data" 

" partition is lost, so set this bit with care.", 

TypeConverters.toBoolean) 

 

def __init__(self, *args): 

super(_LDAParams, self).__init__(*args) 

self._setDefault(maxIter=20, checkpointInterval=10, 

k=10, optimizer="online", learningOffset=1024.0, learningDecay=0.51, 

subsamplingRate=0.05, optimizeDocConcentration=True, 

topicDistributionCol="topicDistribution", keepLastCheckpoint=True) 

 

@since("2.0.0") 

def getK(self): 

""" 

Gets the value of :py:attr:`k` or its default value. 

""" 

return self.getOrDefault(self.k) 

 

@since("2.0.0") 

def getOptimizer(self): 

""" 

Gets the value of :py:attr:`optimizer` or its default value. 

""" 

return self.getOrDefault(self.optimizer) 

 

@since("2.0.0") 

def getLearningOffset(self): 

""" 

Gets the value of :py:attr:`learningOffset` or its default value. 

""" 

return self.getOrDefault(self.learningOffset) 

 

@since("2.0.0") 

def getLearningDecay(self): 

""" 

Gets the value of :py:attr:`learningDecay` or its default value. 

""" 

return self.getOrDefault(self.learningDecay) 

 

@since("2.0.0") 

def getSubsamplingRate(self): 

""" 

Gets the value of :py:attr:`subsamplingRate` or its default value. 

""" 

return self.getOrDefault(self.subsamplingRate) 

 

@since("2.0.0") 

def getOptimizeDocConcentration(self): 

""" 

Gets the value of :py:attr:`optimizeDocConcentration` or its default value. 

""" 

return self.getOrDefault(self.optimizeDocConcentration) 

 

@since("2.0.0") 

def getDocConcentration(self): 

""" 

Gets the value of :py:attr:`docConcentration` or its default value. 

""" 

return self.getOrDefault(self.docConcentration) 

 

@since("2.0.0") 

def getTopicConcentration(self): 

""" 

Gets the value of :py:attr:`topicConcentration` or its default value. 

""" 

return self.getOrDefault(self.topicConcentration) 

 

@since("2.0.0") 

def getTopicDistributionCol(self): 

""" 

Gets the value of :py:attr:`topicDistributionCol` or its default value. 

""" 

return self.getOrDefault(self.topicDistributionCol) 

 

@since("2.0.0") 

def getKeepLastCheckpoint(self): 

""" 

Gets the value of :py:attr:`keepLastCheckpoint` or its default value. 

""" 

return self.getOrDefault(self.keepLastCheckpoint) 

 

 

@inherit_doc 

class LDAModel(JavaModel, _LDAParams): 

""" 

Latent Dirichlet Allocation (LDA) model. 

This abstraction permits for different underlying representations, 

including local and distributed data structures. 

 

.. versionadded:: 2.0.0 

""" 

 

@since("3.0.0") 

def setFeaturesCol(self, value): 

""" 

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

""" 

return self._set(featuresCol=value) 

 

@since("3.0.0") 

def setSeed(self, value): 

""" 

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

""" 

return self._set(seed=value) 

 

@since("3.0.0") 

def setTopicDistributionCol(self, value): 

""" 

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

""" 

return self._set(topicDistributionCol=value) 

 

@since("2.0.0") 

def isDistributed(self): 

""" 

Indicates whether this instance is of type DistributedLDAModel 

""" 

return self._call_java("isDistributed") 

 

@since("2.0.0") 

def vocabSize(self): 

"""Vocabulary size (number of terms or words in the vocabulary)""" 

return self._call_java("vocabSize") 

 

@since("2.0.0") 

def topicsMatrix(self): 

""" 

Inferred topics, where each topic is represented by a distribution over terms. 

This is a matrix of size vocabSize x k, where each column is a topic. 

No guarantees are given about the ordering of the topics. 

 

.. warning:: If this model is actually a :py:class:`DistributedLDAModel` 

instance produced by the Expectation-Maximization ("em") `optimizer`, 

then this method could involve collecting a large amount of data 

to the driver (on the order of vocabSize x k). 

""" 

return self._call_java("topicsMatrix") 

 

@since("2.0.0") 

def logLikelihood(self, dataset): 

""" 

Calculates a lower bound on the log likelihood of the entire corpus. 

See Equation (16) in the Online LDA paper (Hoffman et al., 2010). 

 

.. warning:: If this model is an instance of :py:class:`DistributedLDAModel` (produced when 

:py:attr:`optimizer` is set to "em"), this involves collecting a large 

:py:func:`topicsMatrix` to the driver. This implementation may be changed in the future. 

""" 

return self._call_java("logLikelihood", dataset) 

 

@since("2.0.0") 

def logPerplexity(self, dataset): 

""" 

Calculate an upper bound on perplexity. (Lower is better.) 

See Equation (16) in the Online LDA paper (Hoffman et al., 2010). 

 

.. warning:: If this model is an instance of :py:class:`DistributedLDAModel` (produced when 

:py:attr:`optimizer` is set to "em"), this involves collecting a large 

:py:func:`topicsMatrix` to the driver. This implementation may be changed in the future. 

""" 

return self._call_java("logPerplexity", dataset) 

 

@since("2.0.0") 

def describeTopics(self, maxTermsPerTopic=10): 

""" 

Return the topics described by their top-weighted terms. 

""" 

return self._call_java("describeTopics", maxTermsPerTopic) 

 

@since("2.0.0") 

def estimatedDocConcentration(self): 

""" 

Value for :py:attr:`LDA.docConcentration` estimated from data. 

If Online LDA was used and :py:attr:`LDA.optimizeDocConcentration` was set to false, 

then this returns the fixed (given) value for the :py:attr:`LDA.docConcentration` parameter. 

""" 

return self._call_java("estimatedDocConcentration") 

 

 

@inherit_doc 

class DistributedLDAModel(LDAModel, JavaMLReadable, JavaMLWritable): 

""" 

Distributed model fitted by :py:class:`LDA`. 

This type of model is currently only produced by Expectation-Maximization (EM). 

 

This model stores the inferred topics, the full training dataset, and the topic distribution 

for each training document. 

 

.. versionadded:: 2.0.0 

""" 

 

@since("2.0.0") 

def toLocal(self): 

""" 

Convert this distributed model to a local representation. This discards info about the 

training dataset. 

 

.. warning:: This involves collecting a large :py:func:`topicsMatrix` to the driver. 

""" 

model = LocalLDAModel(self._call_java("toLocal")) 

 

# SPARK-10931: Temporary fix to be removed once LDAModel defines Params 

model._create_params_from_java() 

model._transfer_params_from_java() 

 

return model 

 

@since("2.0.0") 

def trainingLogLikelihood(self): 

""" 

Log likelihood of the observed tokens in the training set, 

given the current parameter estimates: 

log P(docs | topics, topic distributions for docs, Dirichlet hyperparameters) 

 

Notes 

----- 

- This excludes the prior; for that, use :py:func:`logPrior`. 

- Even with :py:func:`logPrior`, this is NOT the same as the data log likelihood given 

the hyperparameters. 

- This is computed from the topic distributions computed during training. If you call 

:py:func:`logLikelihood` on the same training dataset, the topic distributions 

will be computed again, possibly giving different results. 

""" 

return self._call_java("trainingLogLikelihood") 

 

@since("2.0.0") 

def logPrior(self): 

""" 

Log probability of the current parameter estimate: 

log P(topics, topic distributions for docs | alpha, eta) 

""" 

return self._call_java("logPrior") 

 

def getCheckpointFiles(self): 

""" 

If using checkpointing and :py:attr:`LDA.keepLastCheckpoint` is set to true, then there may 

be saved checkpoint files. This method is provided so that users can manage those files. 

 

.. versionadded:: 2.0.0 

 

Returns 

------- 

list 

List of checkpoint files from training 

 

Notes 

----- 

Removing the checkpoints can cause failures if a partition is lost and is needed 

by certain :py:class:`DistributedLDAModel` methods. Reference counting will clean up 

the checkpoints when this model and derivative data go out of scope. 

""" 

return self._call_java("getCheckpointFiles") 

 

 

@inherit_doc 

class LocalLDAModel(LDAModel, JavaMLReadable, JavaMLWritable): 

""" 

Local (non-distributed) model fitted by :py:class:`LDA`. 

This model stores the inferred topics only; it does not store info about the training dataset. 

 

.. versionadded:: 2.0.0 

""" 

pass 

 

 

@inherit_doc 

class LDA(JavaEstimator, _LDAParams, JavaMLReadable, JavaMLWritable): 

""" 

Latent Dirichlet Allocation (LDA), a topic model designed for text documents. 

 

Terminology: 

 

- "term" = "word": an element of the vocabulary 

- "token": instance of a term appearing in a document 

- "topic": multinomial distribution over terms representing some concept 

- "document": one piece of text, corresponding to one row in the input data 

 

Original LDA paper (journal version): 

Blei, Ng, and Jordan. "Latent Dirichlet Allocation." JMLR, 2003. 

 

Input data (featuresCol): 

LDA is given a collection of documents as input data, via the featuresCol parameter. 

Each document is specified as a :py:class:`Vector` of length vocabSize, where each entry is the 

count for the corresponding term (word) in the document. Feature transformers such as 

:py:class:`pyspark.ml.feature.Tokenizer` and :py:class:`pyspark.ml.feature.CountVectorizer` 

can be useful for converting text to word count vectors. 

 

.. versionadded:: 2.0.0 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors, SparseVector 

>>> from pyspark.ml.clustering import LDA 

>>> df = spark.createDataFrame([[1, Vectors.dense([0.0, 1.0])], 

... [2, SparseVector(2, {0: 1.0})],], ["id", "features"]) 

>>> lda = LDA(k=2, seed=1, optimizer="em") 

>>> lda.setMaxIter(10) 

LDA... 

>>> lda.getMaxIter() 

10 

>>> lda.clear(lda.maxIter) 

>>> model = lda.fit(df) 

>>> model.setSeed(1) 

DistributedLDAModel... 

>>> model.getTopicDistributionCol() 

'topicDistribution' 

>>> model.isDistributed() 

True 

>>> localModel = model.toLocal() 

>>> localModel.isDistributed() 

False 

>>> model.vocabSize() 

2 

>>> model.describeTopics().show() 

+-----+-----------+--------------------+ 

|topic|termIndices| termWeights| 

+-----+-----------+--------------------+ 

| 0| [1, 0]|[0.50401530077160...| 

| 1| [0, 1]|[0.50401530077160...| 

+-----+-----------+--------------------+ 

... 

>>> model.topicsMatrix() 

DenseMatrix(2, 2, [0.496, 0.504, 0.504, 0.496], 0) 

>>> lda_path = temp_path + "/lda" 

>>> lda.save(lda_path) 

>>> sameLDA = LDA.load(lda_path) 

>>> distributed_model_path = temp_path + "/lda_distributed_model" 

>>> model.save(distributed_model_path) 

>>> sameModel = DistributedLDAModel.load(distributed_model_path) 

>>> local_model_path = temp_path + "/lda_local_model" 

>>> localModel.save(local_model_path) 

>>> sameLocalModel = LocalLDAModel.load(local_model_path) 

>>> model.transform(df).take(1) == sameLocalModel.transform(df).take(1) 

True 

""" 

 

@keyword_only 

def __init__(self, *, featuresCol="features", maxIter=20, seed=None, checkpointInterval=10, 

k=10, optimizer="online", learningOffset=1024.0, learningDecay=0.51, 

subsamplingRate=0.05, optimizeDocConcentration=True, 

docConcentration=None, topicConcentration=None, 

topicDistributionCol="topicDistribution", keepLastCheckpoint=True): 

""" 

__init__(self, \\*, featuresCol="features", maxIter=20, seed=None, checkpointInterval=10,\ 

k=10, optimizer="online", learningOffset=1024.0, learningDecay=0.51,\ 

subsamplingRate=0.05, optimizeDocConcentration=True,\ 

docConcentration=None, topicConcentration=None,\ 

topicDistributionCol="topicDistribution", keepLastCheckpoint=True) 

""" 

super(LDA, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.clustering.LDA", self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

def _create_model(self, java_model): 

1432 ↛ 1435line 1432 didn't jump to line 1435, because the condition on line 1432 was never false if self.getOptimizer() == "em": 

return DistributedLDAModel(java_model) 

else: 

return LocalLDAModel(java_model) 

 

@keyword_only 

@since("2.0.0") 

def setParams(self, *, featuresCol="features", maxIter=20, seed=None, checkpointInterval=10, 

k=10, optimizer="online", learningOffset=1024.0, learningDecay=0.51, 

subsamplingRate=0.05, optimizeDocConcentration=True, 

docConcentration=None, topicConcentration=None, 

topicDistributionCol="topicDistribution", keepLastCheckpoint=True): 

""" 

setParams(self, \\*, featuresCol="features", maxIter=20, seed=None, checkpointInterval=10,\ 

k=10, optimizer="online", learningOffset=1024.0, learningDecay=0.51,\ 

subsamplingRate=0.05, optimizeDocConcentration=True,\ 

docConcentration=None, topicConcentration=None,\ 

topicDistributionCol="topicDistribution", keepLastCheckpoint=True) 

 

Sets params for LDA. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("2.0.0") 

def setCheckpointInterval(self, value): 

""" 

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

""" 

return self._set(checkpointInterval=value) 

 

@since("2.0.0") 

def setSeed(self, value): 

""" 

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

""" 

return self._set(seed=value) 

 

@since("2.0.0") 

def setK(self, value): 

""" 

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

 

>>> algo = LDA().setK(10) 

>>> algo.getK() 

10 

""" 

return self._set(k=value) 

 

@since("2.0.0") 

def setOptimizer(self, value): 

""" 

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

Currently only support 'em' and 'online'. 

 

Examples 

-------- 

>>> algo = LDA().setOptimizer("em") 

>>> algo.getOptimizer() 

'em' 

""" 

return self._set(optimizer=value) 

 

@since("2.0.0") 

def setLearningOffset(self, value): 

""" 

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

 

Examples 

-------- 

>>> algo = LDA().setLearningOffset(100) 

>>> algo.getLearningOffset() 

100.0 

""" 

return self._set(learningOffset=value) 

 

@since("2.0.0") 

def setLearningDecay(self, value): 

""" 

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

 

Examples 

-------- 

>>> algo = LDA().setLearningDecay(0.1) 

>>> algo.getLearningDecay() 

0.1... 

""" 

return self._set(learningDecay=value) 

 

@since("2.0.0") 

def setSubsamplingRate(self, value): 

""" 

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

 

Examples 

-------- 

>>> algo = LDA().setSubsamplingRate(0.1) 

>>> algo.getSubsamplingRate() 

0.1... 

""" 

return self._set(subsamplingRate=value) 

 

@since("2.0.0") 

def setOptimizeDocConcentration(self, value): 

""" 

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

 

Examples 

-------- 

>>> algo = LDA().setOptimizeDocConcentration(True) 

>>> algo.getOptimizeDocConcentration() 

True 

""" 

return self._set(optimizeDocConcentration=value) 

 

@since("2.0.0") 

def setDocConcentration(self, value): 

""" 

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

 

Examples 

-------- 

>>> algo = LDA().setDocConcentration([0.1, 0.2]) 

>>> algo.getDocConcentration() 

[0.1..., 0.2...] 

""" 

return self._set(docConcentration=value) 

 

@since("2.0.0") 

def setTopicConcentration(self, value): 

""" 

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

 

Examples 

-------- 

>>> algo = LDA().setTopicConcentration(0.5) 

>>> algo.getTopicConcentration() 

0.5... 

""" 

return self._set(topicConcentration=value) 

 

@since("2.0.0") 

def setTopicDistributionCol(self, value): 

""" 

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

 

Examples 

-------- 

>>> algo = LDA().setTopicDistributionCol("topicDistributionCol") 

>>> algo.getTopicDistributionCol() 

'topicDistributionCol' 

""" 

return self._set(topicDistributionCol=value) 

 

@since("2.0.0") 

def setKeepLastCheckpoint(self, value): 

""" 

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

 

Examples 

-------- 

>>> algo = LDA().setKeepLastCheckpoint(False) 

>>> algo.getKeepLastCheckpoint() 

False 

""" 

return self._set(keepLastCheckpoint=value) 

 

@since("2.0.0") 

def setMaxIter(self, value): 

""" 

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

""" 

return self._set(maxIter=value) 

 

@since("2.0.0") 

def setFeaturesCol(self, value): 

""" 

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

""" 

return self._set(featuresCol=value) 

 

 

@inherit_doc 

class _PowerIterationClusteringParams(HasMaxIter, HasWeightCol): 

""" 

Params for :py:class:`PowerIterationClustering`. 

 

.. versionadded:: 3.0.0 

""" 

 

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

"The number of clusters to create. Must be > 1.", 

typeConverter=TypeConverters.toInt) 

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

"The initialization algorithm. This can be either " + 

"'random' to use a random vector as vertex properties, or 'degree' to use " + 

"a normalized sum of similarities with other vertices. Supported options: " + 

"'random' and 'degree'.", 

typeConverter=TypeConverters.toString) 

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

"Name of the input column for source vertex IDs.", 

typeConverter=TypeConverters.toString) 

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

"Name of the input column for destination vertex IDs.", 

typeConverter=TypeConverters.toString) 

 

def __init__(self, *args): 

super(_PowerIterationClusteringParams, self).__init__(*args) 

self._setDefault(k=2, maxIter=20, initMode="random", srcCol="src", dstCol="dst") 

 

@since("2.4.0") 

def getK(self): 

""" 

Gets the value of :py:attr:`k` or its default value. 

""" 

return self.getOrDefault(self.k) 

 

@since("2.4.0") 

def getInitMode(self): 

""" 

Gets the value of :py:attr:`initMode` or its default value. 

""" 

return self.getOrDefault(self.initMode) 

 

@since("2.4.0") 

def getSrcCol(self): 

""" 

Gets the value of :py:attr:`srcCol` or its default value. 

""" 

return self.getOrDefault(self.srcCol) 

 

@since("2.4.0") 

def getDstCol(self): 

""" 

Gets the value of :py:attr:`dstCol` or its default value. 

""" 

return self.getOrDefault(self.dstCol) 

 

 

@inherit_doc 

class PowerIterationClustering(_PowerIterationClusteringParams, JavaParams, JavaMLReadable, 

JavaMLWritable): 

""" 

Power Iteration Clustering (PIC), a scalable graph clustering algorithm developed by 

`Lin and Cohen <http://www.cs.cmu.edu/~frank/papers/icml2010-pic-final.pdf>`_. From the 

abstract: PIC finds a very low-dimensional embedding of a dataset using truncated power 

iteration on a normalized pair-wise similarity matrix of the data. 

 

This class is not yet an Estimator/Transformer, use :py:func:`assignClusters` method 

to run the PowerIterationClustering algorithm. 

 

.. versionadded:: 2.4.0 

 

Notes 

----- 

See `Wikipedia on Spectral clustering <http://en.wikipedia.org/wiki/Spectral_clustering>`_ 

 

Examples 

-------- 

>>> data = [(1, 0, 0.5), 

... (2, 0, 0.5), (2, 1, 0.7), 

... (3, 0, 0.5), (3, 1, 0.7), (3, 2, 0.9), 

... (4, 0, 0.5), (4, 1, 0.7), (4, 2, 0.9), (4, 3, 1.1), 

... (5, 0, 0.5), (5, 1, 0.7), (5, 2, 0.9), (5, 3, 1.1), (5, 4, 1.3)] 

>>> df = spark.createDataFrame(data).toDF("src", "dst", "weight").repartition(1) 

>>> pic = PowerIterationClustering(k=2, weightCol="weight") 

>>> pic.setMaxIter(40) 

PowerIterationClustering... 

>>> assignments = pic.assignClusters(df) 

>>> assignments.sort(assignments.id).show(truncate=False) 

+---+-------+ 

|id |cluster| 

+---+-------+ 

|0 |0 | 

|1 |0 | 

|2 |0 | 

|3 |0 | 

|4 |0 | 

|5 |1 | 

+---+-------+ 

... 

>>> pic_path = temp_path + "/pic" 

>>> pic.save(pic_path) 

>>> pic2 = PowerIterationClustering.load(pic_path) 

>>> pic2.getK() 

2 

>>> pic2.getMaxIter() 

40 

>>> pic2.assignClusters(df).take(6) == assignments.take(6) 

True 

""" 

 

@keyword_only 

def __init__(self, *, k=2, maxIter=20, initMode="random", srcCol="src", dstCol="dst", 

weightCol=None): 

""" 

__init__(self, \\*, k=2, maxIter=20, initMode="random", srcCol="src", dstCol="dst",\ 

weightCol=None) 

""" 

super(PowerIterationClustering, self).__init__() 

self._java_obj = self._new_java_obj( 

"org.apache.spark.ml.clustering.PowerIterationClustering", self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("2.4.0") 

def setParams(self, *, k=2, maxIter=20, initMode="random", srcCol="src", dstCol="dst", 

weightCol=None): 

""" 

setParams(self, \\*, k=2, maxIter=20, initMode="random", srcCol="src", dstCol="dst",\ 

weightCol=None) 

Sets params for PowerIterationClustering. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("2.4.0") 

def setK(self, value): 

""" 

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

""" 

return self._set(k=value) 

 

@since("2.4.0") 

def setInitMode(self, value): 

""" 

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

""" 

return self._set(initMode=value) 

 

@since("2.4.0") 

def setSrcCol(self, value): 

""" 

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

""" 

return self._set(srcCol=value) 

 

@since("2.4.0") 

def setDstCol(self, value): 

""" 

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

""" 

return self._set(dstCol=value) 

 

@since("2.4.0") 

def setMaxIter(self, value): 

""" 

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

""" 

return self._set(maxIter=value) 

 

@since("2.4.0") 

def setWeightCol(self, value): 

""" 

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

""" 

return self._set(weightCol=value) 

 

@since("2.4.0") 

def assignClusters(self, dataset): 

""" 

Run the PIC algorithm and returns a cluster assignment for each input vertex. 

 

Parameters 

---------- 

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

A dataset with columns src, dst, weight representing the affinity matrix, 

which is the matrix A in the PIC paper. Suppose the src column value is i, 

the dst column value is j, the weight column value is similarity s,,ij,, 

which must be nonnegative. This is a symmetric matrix and hence 

s,,ij,, = s,,ji,,. For any (i, j) with nonzero similarity, there should be 

either (i, j, s,,ij,,) or (j, i, s,,ji,,) in the input. Rows with i = j are 

ignored, because we assume s,,ij,, = 0.0. 

 

Returns 

------- 

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

A dataset that contains columns of vertex id and the corresponding cluster for 

the id. The schema of it will be: 

- id: Long 

- cluster: Int 

""" 

self._transfer_params_to_java() 

jdf = self._java_obj.assignClusters(dataset._jdf) 

return DataFrame(jdf, dataset.sql_ctx) 

 

 

if __name__ == "__main__": 

import doctest 

import numpy 

import pyspark.ml.clustering 

from pyspark.sql import SparkSession 

try: 

# Numpy 1.14+ changed it's string format. 

numpy.set_printoptions(legacy='1.13') 

except TypeError: 

pass 

globs = pyspark.ml.clustering.__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.clustering tests")\ 

.getOrCreate() 

sc = spark.sparkContext 

globs['sc'] = sc 

globs['spark'] = spark 

import tempfile 

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 

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

sys.exit(-1)