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

# 

# 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. 

# 

 

""" 

Package for distributed linear algebra. 

""" 

 

import sys 

 

from py4j.java_gateway import JavaObject 

 

from pyspark import RDD, since 

from pyspark.mllib.common import callMLlibFunc, JavaModelWrapper 

from pyspark.mllib.linalg import _convert_to_vector, DenseMatrix, Matrix, QRDecomposition 

from pyspark.mllib.stat import MultivariateStatisticalSummary 

from pyspark.sql import DataFrame 

from pyspark.storagelevel import StorageLevel 

 

 

__all__ = ['BlockMatrix', 'CoordinateMatrix', 'DistributedMatrix', 'IndexedRow', 

'IndexedRowMatrix', 'MatrixEntry', 'RowMatrix', 'SingularValueDecomposition'] 

 

 

class DistributedMatrix(object): 

""" 

Represents a distributively stored matrix backed by one or 

more RDDs. 

 

""" 

def numRows(self): 

"""Get or compute the number of rows.""" 

raise NotImplementedError 

 

def numCols(self): 

"""Get or compute the number of cols.""" 

raise NotImplementedError 

 

 

class RowMatrix(DistributedMatrix): 

""" 

Represents a row-oriented distributed Matrix with no meaningful 

row indices. 

 

 

Parameters 

---------- 

rows : :py:class:`pyspark.RDD` or :py:class:`pyspark.sql.DataFrame` 

An RDD or DataFrame of vectors. If a DataFrame is provided, it must have a single 

vector typed column. 

numRows : int, optional 

Number of rows in the matrix. A non-positive 

value means unknown, at which point the number 

of rows will be determined by the number of 

records in the `rows` RDD. 

numCols : int, optional 

Number of columns in the matrix. A non-positive 

value means unknown, at which point the number 

of columns will be determined by the size of 

the first row. 

""" 

def __init__(self, rows, numRows=0, numCols=0): 

""" 

Note: This docstring is not shown publicly. 

 

Create a wrapper over a Java RowMatrix. 

 

Publicly, we require that `rows` be an RDD or DataFrame. However, for 

internal usage, `rows` can also be a Java RowMatrix 

object, in which case we can wrap it directly. This 

assists in clean matrix conversions. 

 

Examples 

-------- 

>>> rows = sc.parallelize([[1, 2, 3], [4, 5, 6]]) 

>>> mat = RowMatrix(rows) 

 

>>> mat_diff = RowMatrix(rows) 

>>> (mat_diff._java_matrix_wrapper._java_model == 

... mat._java_matrix_wrapper._java_model) 

False 

 

>>> mat_same = RowMatrix(mat._java_matrix_wrapper._java_model) 

>>> (mat_same._java_matrix_wrapper._java_model == 

... mat._java_matrix_wrapper._java_model) 

True 

""" 

if isinstance(rows, RDD): 

rows = rows.map(_convert_to_vector) 

java_matrix = callMLlibFunc("createRowMatrix", rows, int(numRows), int(numCols)) 

elif isinstance(rows, DataFrame): 

java_matrix = callMLlibFunc("createRowMatrix", rows, int(numRows), int(numCols)) 

106 ↛ 110line 106 didn't jump to line 110, because the condition on line 106 was never false elif (isinstance(rows, JavaObject) 

and rows.getClass().getSimpleName() == "RowMatrix"): 

java_matrix = rows 

else: 

raise TypeError("rows should be an RDD of vectors, got %s" % type(rows)) 

 

self._java_matrix_wrapper = JavaModelWrapper(java_matrix) 

 

@property 

def rows(self): 

""" 

Rows of the RowMatrix stored as an RDD of vectors. 

 

Examples 

-------- 

>>> mat = RowMatrix(sc.parallelize([[1, 2, 3], [4, 5, 6]])) 

>>> rows = mat.rows 

>>> rows.first() 

DenseVector([1.0, 2.0, 3.0]) 

""" 

return self._java_matrix_wrapper.call("rows") 

 

def numRows(self): 

""" 

Get or compute the number of rows. 

 

Examples 

-------- 

>>> rows = sc.parallelize([[1, 2, 3], [4, 5, 6], 

... [7, 8, 9], [10, 11, 12]]) 

 

>>> mat = RowMatrix(rows) 

>>> print(mat.numRows()) 

4 

 

>>> mat = RowMatrix(rows, 7, 6) 

>>> print(mat.numRows()) 

7 

""" 

return self._java_matrix_wrapper.call("numRows") 

 

def numCols(self): 

""" 

Get or compute the number of cols. 

 

Examples 

-------- 

>>> rows = sc.parallelize([[1, 2, 3], [4, 5, 6], 

... [7, 8, 9], [10, 11, 12]]) 

 

>>> mat = RowMatrix(rows) 

>>> print(mat.numCols()) 

3 

 

>>> mat = RowMatrix(rows, 7, 6) 

>>> print(mat.numCols()) 

6 

""" 

return self._java_matrix_wrapper.call("numCols") 

 

def computeColumnSummaryStatistics(self): 

""" 

Computes column-wise summary statistics. 

 

.. versionadded:: 2.0.0 

 

Returns 

------- 

:py:class:`MultivariateStatisticalSummary` 

object containing column-wise summary statistics. 

 

Examples 

-------- 

>>> rows = sc.parallelize([[1, 2, 3], [4, 5, 6]]) 

>>> mat = RowMatrix(rows) 

 

>>> colStats = mat.computeColumnSummaryStatistics() 

>>> colStats.mean() 

array([ 2.5, 3.5, 4.5]) 

""" 

java_col_stats = self._java_matrix_wrapper.call("computeColumnSummaryStatistics") 

return MultivariateStatisticalSummary(java_col_stats) 

 

def computeCovariance(self): 

""" 

Computes the covariance matrix, treating each row as an 

observation. 

 

.. versionadded:: 2.0.0 

 

Notes 

----- 

This cannot be computed on matrices with more than 65535 columns. 

 

Examples 

-------- 

>>> rows = sc.parallelize([[1, 2], [2, 1]]) 

>>> mat = RowMatrix(rows) 

 

>>> mat.computeCovariance() 

DenseMatrix(2, 2, [0.5, -0.5, -0.5, 0.5], 0) 

""" 

return self._java_matrix_wrapper.call("computeCovariance") 

 

def computeGramianMatrix(self): 

""" 

Computes the Gramian matrix `A^T A`. 

 

.. versionadded:: 2.0.0 

 

Notes 

----- 

This cannot be computed on matrices with more than 65535 columns. 

 

Examples 

-------- 

>>> rows = sc.parallelize([[1, 2, 3], [4, 5, 6]]) 

>>> mat = RowMatrix(rows) 

 

>>> mat.computeGramianMatrix() 

DenseMatrix(3, 3, [17.0, 22.0, 27.0, 22.0, 29.0, 36.0, 27.0, 36.0, 45.0], 0) 

""" 

return self._java_matrix_wrapper.call("computeGramianMatrix") 

 

@since('2.0.0') 

def columnSimilarities(self, threshold=0.0): 

""" 

Compute similarities between columns of this matrix. 

 

The threshold parameter is a trade-off knob between estimate 

quality and computational cost. 

 

The default threshold setting of 0 guarantees deterministically 

correct results, but uses the brute-force approach of computing 

normalized dot products. 

 

Setting the threshold to positive values uses a sampling 

approach and incurs strictly less computational cost than the 

brute-force approach. However the similarities computed will 

be estimates. 

 

The sampling guarantees relative-error correctness for those 

pairs of columns that have similarity greater than the given 

similarity threshold. 

 

To describe the guarantee, we set some notation: 

 

- Let A be the smallest in magnitude non-zero element of 

this matrix. 

- Let B be the largest in magnitude non-zero element of 

this matrix. 

- Let L be the maximum number of non-zeros per row. 

 

For example, for {0,1} matrices: A=B=1. 

Another example, for the Netflix matrix: A=1, B=5 

 

For those column pairs that are above the threshold, the 

computed similarity is correct to within 20% relative error 

with probability at least 1 - (0.981)^10/B^ 

 

The shuffle size is bounded by the *smaller* of the following 

two expressions: 

 

- O(n log(n) L / (threshold * A)) 

- O(m L^2^) 

 

The latter is the cost of the brute-force approach, so for 

non-zero thresholds, the cost is always cheaper than the 

brute-force approach. 

 

.. versionadded:: 2.0.0 

 

Parameters 

---------- 

threshold : float, optional 

Set to 0 for deterministic guaranteed 

correctness. Similarities above this 

threshold are estimated with the cost vs 

estimate quality trade-off described above. 

 

Returns 

------- 

:py:class:`CoordinateMatrix` 

An n x n sparse upper-triangular CoordinateMatrix of 

cosine similarities between columns of this matrix. 

 

Examples 

-------- 

>>> rows = sc.parallelize([[1, 2], [1, 5]]) 

>>> mat = RowMatrix(rows) 

 

>>> sims = mat.columnSimilarities() 

>>> sims.entries.first().value 

0.91914503... 

""" 

java_sims_mat = self._java_matrix_wrapper.call("columnSimilarities", float(threshold)) 

return CoordinateMatrix(java_sims_mat) 

 

def tallSkinnyQR(self, computeQ=False): 

""" 

Compute the QR decomposition of this RowMatrix. 

 

The implementation is designed to optimize the QR decomposition 

(factorization) for the RowMatrix of a tall and skinny shape [1]_. 

 

.. [1] Paul G. Constantine, David F. Gleich. "Tall and skinny QR 

factorizations in MapReduce architectures" 

https://doi.org/10.1145/1996092.1996103 

 

.. versionadded:: 2.0.0 

 

Parameters 

---------- 

computeQ : bool, optional 

whether to computeQ 

 

Returns 

------- 

:py:class:`pyspark.mllib.linalg.QRDecomposition` 

QRDecomposition(Q: RowMatrix, R: Matrix), where 

Q = None if computeQ = false. 

 

Examples 

-------- 

>>> rows = sc.parallelize([[3, -6], [4, -8], [0, 1]]) 

>>> mat = RowMatrix(rows) 

>>> decomp = mat.tallSkinnyQR(True) 

>>> Q = decomp.Q 

>>> R = decomp.R 

 

>>> # Test with absolute values 

>>> absQRows = Q.rows.map(lambda row: abs(row.toArray()).tolist()) 

>>> absQRows.collect() 

[[0.6..., 0.0], [0.8..., 0.0], [0.0, 1.0]] 

 

>>> # Test with absolute values 

>>> abs(R.toArray()).tolist() 

[[5.0, 10.0], [0.0, 1.0]] 

""" 

decomp = JavaModelWrapper(self._java_matrix_wrapper.call("tallSkinnyQR", computeQ)) 

346 ↛ 350line 346 didn't jump to line 350, because the condition on line 346 was never false if computeQ: 

java_Q = decomp.call("Q") 

Q = RowMatrix(java_Q) 

else: 

Q = None 

R = decomp.call("R") 

return QRDecomposition(Q, R) 

 

def computeSVD(self, k, computeU=False, rCond=1e-9): 

""" 

Computes the singular value decomposition of the RowMatrix. 

 

The given row matrix A of dimension (m X n) is decomposed into 

U * s * V'T where 

 

- U: (m X k) (left singular vectors) is a RowMatrix whose 

columns are the eigenvectors of (A X A') 

- s: DenseVector consisting of square root of the eigenvalues 

(singular values) in descending order. 

- v: (n X k) (right singular vectors) is a Matrix whose columns 

are the eigenvectors of (A' X A) 

 

For more specific details on implementation, please refer 

the Scala documentation. 

 

.. versionadded:: 2.2.0 

 

Parameters 

---------- 

k : int 

Number of leading singular values to keep (`0 < k <= n`). 

It might return less than k if there are numerically zero singular values 

or there are not enough Ritz values converged before the maximum number of 

Arnoldi update iterations is reached (in case that matrix A is ill-conditioned). 

computeU : bool, optional 

Whether or not to compute U. If set to be 

True, then U is computed by A * V * s^-1 

rCond : float, optional 

Reciprocal condition number. All singular values 

smaller than rCond * s[0] are treated as zero 

where s[0] is the largest singular value. 

 

Returns 

------- 

:py:class:`SingularValueDecomposition` 

 

Examples 

-------- 

>>> rows = sc.parallelize([[3, 1, 1], [-1, 3, 1]]) 

>>> rm = RowMatrix(rows) 

 

>>> svd_model = rm.computeSVD(2, True) 

>>> svd_model.U.rows.collect() 

[DenseVector([-0.7071, 0.7071]), DenseVector([-0.7071, -0.7071])] 

>>> svd_model.s 

DenseVector([3.4641, 3.1623]) 

>>> svd_model.V 

DenseMatrix(3, 2, [-0.4082, -0.8165, -0.4082, 0.8944, -0.4472, 0.0], 0) 

""" 

j_model = self._java_matrix_wrapper.call( 

"computeSVD", int(k), bool(computeU), float(rCond)) 

return SingularValueDecomposition(j_model) 

 

def computePrincipalComponents(self, k): 

""" 

Computes the k principal components of the given row matrix 

 

.. versionadded:: 2.2.0 

 

Notes 

----- 

This cannot be computed on matrices with more than 65535 columns. 

 

Parameters 

---------- 

k : int 

Number of principal components to keep. 

 

Returns 

------- 

:py:class:`pyspark.mllib.linalg.DenseMatrix` 

 

Examples 

-------- 

>>> rows = sc.parallelize([[1, 2, 3], [2, 4, 5], [3, 6, 1]]) 

>>> rm = RowMatrix(rows) 

 

>>> # Returns the two principal components of rm 

>>> pca = rm.computePrincipalComponents(2) 

>>> pca 

DenseMatrix(3, 2, [-0.349, -0.6981, 0.6252, -0.2796, -0.5592, -0.7805], 0) 

 

>>> # Transform into new dimensions with the greatest variance. 

>>> rm.multiply(pca).rows.collect() # doctest: +NORMALIZE_WHITESPACE 

[DenseVector([0.1305, -3.7394]), DenseVector([-0.3642, -6.6983]), \ 

DenseVector([-4.6102, -4.9745])] 

""" 

return self._java_matrix_wrapper.call("computePrincipalComponents", k) 

 

def multiply(self, matrix): 

""" 

Multiply this matrix by a local dense matrix on the right. 

 

.. versionadded:: 2.2.0 

 

Parameters 

---------- 

matrix : :py:class:`pyspark.mllib.linalg.Matrix` 

a local dense matrix whose number of rows must match the number of columns 

of this matrix 

 

Returns 

------- 

:py:class:`RowMatrix` 

 

Examples 

-------- 

>>> rm = RowMatrix(sc.parallelize([[0, 1], [2, 3]])) 

>>> rm.multiply(DenseMatrix(2, 2, [0, 2, 1, 3])).rows.collect() 

[DenseVector([2.0, 3.0]), DenseVector([6.0, 11.0])] 

""" 

if not isinstance(matrix, DenseMatrix): 

raise TypeError("Only multiplication with DenseMatrix is supported.") 

j_model = self._java_matrix_wrapper.call("multiply", matrix) 

return RowMatrix(j_model) 

 

 

class SingularValueDecomposition(JavaModelWrapper): 

""" 

Represents singular value decomposition (SVD) factors. 

 

.. versionadded:: 2.2.0 

""" 

 

@property 

@since('2.2.0') 

def U(self): 

""" 

Returns a distributed matrix whose columns are the left 

singular vectors of the SingularValueDecomposition if computeU was set to be True. 

""" 

u = self.call("U") 

if u is not None: 

mat_name = u.getClass().getSimpleName() 

if mat_name == "RowMatrix": 

return RowMatrix(u) 

492 ↛ 495line 492 didn't jump to line 495, because the condition on line 492 was never false elif mat_name == "IndexedRowMatrix": 

return IndexedRowMatrix(u) 

else: 

raise TypeError("Expected RowMatrix/IndexedRowMatrix got %s" % mat_name) 

 

@property 

@since('2.2.0') 

def s(self): 

""" 

Returns a DenseVector with singular values in descending order. 

""" 

return self.call("s") 

 

@property 

@since('2.2.0') 

def V(self): 

""" 

Returns a DenseMatrix whose columns are the right singular 

vectors of the SingularValueDecomposition. 

""" 

return self.call("V") 

 

 

class IndexedRow(object): 

""" 

Represents a row of an IndexedRowMatrix. 

 

Just a wrapper over a (int, vector) tuple. 

 

Parameters 

---------- 

index : int 

The index for the given row. 

vector : :py:class:`pyspark.mllib.linalg.Vector` or convertible 

The row in the matrix at the given index. 

""" 

def __init__(self, index, vector): 

self.index = int(index) 

self.vector = _convert_to_vector(vector) 

 

def __repr__(self): 

return "IndexedRow(%s, %s)" % (self.index, self.vector) 

 

 

def _convert_to_indexed_row(row): 

if isinstance(row, IndexedRow): 

return row 

elif isinstance(row, tuple) and len(row) == 2: 

return IndexedRow(*row) 

else: 

raise TypeError("Cannot convert type %s into IndexedRow" % type(row)) 

 

 

class IndexedRowMatrix(DistributedMatrix): 

""" 

Represents a row-oriented distributed Matrix with indexed rows. 

 

Parameters 

---------- 

rows : :py:class:`pyspark.RDD` 

An RDD of IndexedRows or (int, vector) tuples or a DataFrame consisting of a 

int typed column of indices and a vector typed column. 

numRows : int, optional 

Number of rows in the matrix. A non-positive 

value means unknown, at which point the number 

of rows will be determined by the max row 

index plus one. 

numCols : int, optional 

Number of columns in the matrix. A non-positive 

value means unknown, at which point the number 

of columns will be determined by the size of 

the first row. 

""" 

def __init__(self, rows, numRows=0, numCols=0): 

""" 

Note: This docstring is not shown publicly. 

 

Create a wrapper over a Java IndexedRowMatrix. 

 

Publicly, we require that `rows` be an RDD or DataFrame. However, for 

internal usage, `rows` can also be a Java IndexedRowMatrix 

object, in which case we can wrap it directly. This 

assists in clean matrix conversions. 

 

Examples 

-------- 

>>> rows = sc.parallelize([IndexedRow(0, [1, 2, 3]), 

... IndexedRow(1, [4, 5, 6])]) 

>>> mat = IndexedRowMatrix(rows) 

 

>>> mat_diff = IndexedRowMatrix(rows) 

>>> (mat_diff._java_matrix_wrapper._java_model == 

... mat._java_matrix_wrapper._java_model) 

False 

 

>>> mat_same = IndexedRowMatrix(mat._java_matrix_wrapper._java_model) 

>>> (mat_same._java_matrix_wrapper._java_model == 

... mat._java_matrix_wrapper._java_model) 

True 

""" 

if isinstance(rows, RDD): 

rows = rows.map(_convert_to_indexed_row) 

# We use DataFrames for serialization of IndexedRows from 

# Python, so first convert the RDD to a DataFrame on this 

# side. This will convert each IndexedRow to a Row 

# containing the 'index' and 'vector' values, which can 

# both be easily serialized. We will convert back to 

# IndexedRows on the Scala side. 

java_matrix = callMLlibFunc("createIndexedRowMatrix", rows.toDF(), 

int(numRows), int(numCols)) 

elif isinstance(rows, DataFrame): 

java_matrix = callMLlibFunc("createIndexedRowMatrix", rows, int(numRows), int(numCols)) 

604 ↛ 608line 604 didn't jump to line 608, because the condition on line 604 was never false elif (isinstance(rows, JavaObject) 

and rows.getClass().getSimpleName() == "IndexedRowMatrix"): 

java_matrix = rows 

else: 

raise TypeError("rows should be an RDD of IndexedRows or (int, vector) tuples, " 

"got %s" % type(rows)) 

 

self._java_matrix_wrapper = JavaModelWrapper(java_matrix) 

 

@property 

def rows(self): 

""" 

Rows of the IndexedRowMatrix stored as an RDD of IndexedRows. 

 

Examples 

-------- 

>>> mat = IndexedRowMatrix(sc.parallelize([IndexedRow(0, [1, 2, 3]), 

... IndexedRow(1, [4, 5, 6])])) 

>>> rows = mat.rows 

>>> rows.first() 

IndexedRow(0, [1.0,2.0,3.0]) 

""" 

# We use DataFrames for serialization of IndexedRows from 

# Java, so we first convert the RDD of rows to a DataFrame 

# on the Scala/Java side. Then we map each Row in the 

# DataFrame back to an IndexedRow on this side. 

rows_df = callMLlibFunc("getIndexedRows", self._java_matrix_wrapper._java_model) 

rows = rows_df.rdd.map(lambda row: IndexedRow(row[0], row[1])) 

return rows 

 

def numRows(self): 

""" 

Get or compute the number of rows. 

 

Examples 

-------- 

>>> rows = sc.parallelize([IndexedRow(0, [1, 2, 3]), 

... IndexedRow(1, [4, 5, 6]), 

... IndexedRow(2, [7, 8, 9]), 

... IndexedRow(3, [10, 11, 12])]) 

 

>>> mat = IndexedRowMatrix(rows) 

>>> print(mat.numRows()) 

4 

 

>>> mat = IndexedRowMatrix(rows, 7, 6) 

>>> print(mat.numRows()) 

7 

""" 

return self._java_matrix_wrapper.call("numRows") 

 

def numCols(self): 

""" 

Get or compute the number of cols. 

 

Examples 

-------- 

>>> rows = sc.parallelize([IndexedRow(0, [1, 2, 3]), 

... IndexedRow(1, [4, 5, 6]), 

... IndexedRow(2, [7, 8, 9]), 

... IndexedRow(3, [10, 11, 12])]) 

 

>>> mat = IndexedRowMatrix(rows) 

>>> print(mat.numCols()) 

3 

 

>>> mat = IndexedRowMatrix(rows, 7, 6) 

>>> print(mat.numCols()) 

6 

""" 

return self._java_matrix_wrapper.call("numCols") 

 

def columnSimilarities(self): 

""" 

Compute all cosine similarities between columns. 

 

Examples 

-------- 

>>> rows = sc.parallelize([IndexedRow(0, [1, 2, 3]), 

... IndexedRow(6, [4, 5, 6])]) 

>>> mat = IndexedRowMatrix(rows) 

>>> cs = mat.columnSimilarities() 

>>> print(cs.numCols()) 

3 

""" 

java_coordinate_matrix = self._java_matrix_wrapper.call("columnSimilarities") 

return CoordinateMatrix(java_coordinate_matrix) 

 

def computeGramianMatrix(self): 

""" 

Computes the Gramian matrix `A^T A`. 

 

.. versionadded:: 2.0.0 

 

Notes 

----- 

This cannot be computed on matrices with more than 65535 columns. 

 

Examples 

-------- 

>>> rows = sc.parallelize([IndexedRow(0, [1, 2, 3]), 

... IndexedRow(1, [4, 5, 6])]) 

>>> mat = IndexedRowMatrix(rows) 

 

>>> mat.computeGramianMatrix() 

DenseMatrix(3, 3, [17.0, 22.0, 27.0, 22.0, 29.0, 36.0, 27.0, 36.0, 45.0], 0) 

""" 

return self._java_matrix_wrapper.call("computeGramianMatrix") 

 

def toRowMatrix(self): 

""" 

Convert this matrix to a RowMatrix. 

 

Examples 

-------- 

>>> rows = sc.parallelize([IndexedRow(0, [1, 2, 3]), 

... IndexedRow(6, [4, 5, 6])]) 

>>> mat = IndexedRowMatrix(rows).toRowMatrix() 

>>> mat.rows.collect() 

[DenseVector([1.0, 2.0, 3.0]), DenseVector([4.0, 5.0, 6.0])] 

""" 

java_row_matrix = self._java_matrix_wrapper.call("toRowMatrix") 

return RowMatrix(java_row_matrix) 

 

def toCoordinateMatrix(self): 

""" 

Convert this matrix to a CoordinateMatrix. 

 

Examples 

-------- 

>>> rows = sc.parallelize([IndexedRow(0, [1, 0]), 

... IndexedRow(6, [0, 5])]) 

>>> mat = IndexedRowMatrix(rows).toCoordinateMatrix() 

>>> mat.entries.take(3) 

[MatrixEntry(0, 0, 1.0), MatrixEntry(0, 1, 0.0), MatrixEntry(6, 0, 0.0)] 

""" 

java_coordinate_matrix = self._java_matrix_wrapper.call("toCoordinateMatrix") 

return CoordinateMatrix(java_coordinate_matrix) 

 

def toBlockMatrix(self, rowsPerBlock=1024, colsPerBlock=1024): 

""" 

Convert this matrix to a BlockMatrix. 

 

Parameters 

---------- 

rowsPerBlock : int, optional 

Number of rows that make up each block. 

The blocks forming the final rows are not 

required to have the given number of rows. 

colsPerBlock : int, optional 

Number of columns that make up each block. 

The blocks forming the final columns are not 

required to have the given number of columns. 

 

Examples 

-------- 

>>> rows = sc.parallelize([IndexedRow(0, [1, 2, 3]), 

... IndexedRow(6, [4, 5, 6])]) 

>>> mat = IndexedRowMatrix(rows).toBlockMatrix() 

 

>>> # This IndexedRowMatrix will have 7 effective rows, due to 

>>> # the highest row index being 6, and the ensuing 

>>> # BlockMatrix will have 7 rows as well. 

>>> print(mat.numRows()) 

7 

 

>>> print(mat.numCols()) 

3 

""" 

java_block_matrix = self._java_matrix_wrapper.call("toBlockMatrix", 

rowsPerBlock, 

colsPerBlock) 

return BlockMatrix(java_block_matrix, rowsPerBlock, colsPerBlock) 

 

def computeSVD(self, k, computeU=False, rCond=1e-9): 

""" 

Computes the singular value decomposition of the IndexedRowMatrix. 

 

The given row matrix A of dimension (m X n) is decomposed into 

U * s * V'T where 

 

* U: (m X k) (left singular vectors) is a IndexedRowMatrix 

whose columns are the eigenvectors of (A X A') 

* s: DenseVector consisting of square root of the eigenvalues 

(singular values) in descending order. 

* v: (n X k) (right singular vectors) is a Matrix whose columns 

are the eigenvectors of (A' X A) 

 

For more specific details on implementation, please refer 

the scala documentation. 

 

.. versionadded:: 2.2.0 

 

Parameters 

---------- 

k : int 

Number of leading singular values to keep (`0 < k <= n`). 

It might return less than k if there are numerically zero singular values 

or there are not enough Ritz values converged before the maximum number of 

Arnoldi update iterations is reached (in case that matrix A is ill-conditioned). 

computeU : bool, optional 

Whether or not to compute U. If set to be 

True, then U is computed by A * V * s^-1 

rCond : float, optional 

Reciprocal condition number. All singular values 

smaller than rCond * s[0] are treated as zero 

where s[0] is the largest singular value. 

 

Returns 

------- 

:py:class:`SingularValueDecomposition` 

 

Examples 

-------- 

>>> rows = [(0, (3, 1, 1)), (1, (-1, 3, 1))] 

>>> irm = IndexedRowMatrix(sc.parallelize(rows)) 

>>> svd_model = irm.computeSVD(2, True) 

>>> svd_model.U.rows.collect() # doctest: +NORMALIZE_WHITESPACE 

[IndexedRow(0, [-0.707106781187,0.707106781187]),\ 

IndexedRow(1, [-0.707106781187,-0.707106781187])] 

>>> svd_model.s 

DenseVector([3.4641, 3.1623]) 

>>> svd_model.V 

DenseMatrix(3, 2, [-0.4082, -0.8165, -0.4082, 0.8944, -0.4472, 0.0], 0) 

""" 

j_model = self._java_matrix_wrapper.call( 

"computeSVD", int(k), bool(computeU), float(rCond)) 

return SingularValueDecomposition(j_model) 

 

def multiply(self, matrix): 

""" 

Multiply this matrix by a local dense matrix on the right. 

 

.. versionadded:: 2.2.0 

 

Parameters 

---------- 

matrix : :py:class:`pyspark.mllib.linalg.Matrix` 

a local dense matrix whose number of rows must match the number of columns 

of this matrix 

 

Returns 

------- 

:py:class:`IndexedRowMatrix` 

 

Examples 

-------- 

>>> mat = IndexedRowMatrix(sc.parallelize([(0, (0, 1)), (1, (2, 3))])) 

>>> mat.multiply(DenseMatrix(2, 2, [0, 2, 1, 3])).rows.collect() 

[IndexedRow(0, [2.0,3.0]), IndexedRow(1, [6.0,11.0])] 

""" 

if not isinstance(matrix, DenseMatrix): 

raise TypeError("Only multiplication with DenseMatrix is supported.") 

return IndexedRowMatrix(self._java_matrix_wrapper.call("multiply", matrix)) 

 

 

class MatrixEntry(object): 

""" 

Represents an entry of a CoordinateMatrix. 

 

Just a wrapper over a (int, int, float) tuple. 

 

Parameters 

---------- 

i : int 

The row index of the matrix. 

j : int 

The column index of the matrix. 

value : float 

The (i, j)th entry of the matrix, as a float. 

""" 

def __init__(self, i, j, value): 

self.i = int(i) 

self.j = int(j) 

self.value = float(value) 

 

def __repr__(self): 

return "MatrixEntry(%s, %s, %s)" % (self.i, self.j, self.value) 

 

 

def _convert_to_matrix_entry(entry): 

if isinstance(entry, MatrixEntry): 

return entry 

elif isinstance(entry, tuple) and len(entry) == 3: 

return MatrixEntry(*entry) 

else: 

raise TypeError("Cannot convert type %s into MatrixEntry" % type(entry)) 

 

 

class CoordinateMatrix(DistributedMatrix): 

""" 

Represents a matrix in coordinate format. 

 

Parameters 

---------- 

entries : :py:class:`pyspark.RDD` 

An RDD of MatrixEntry inputs or 

(int, int, float) tuples. 

numRows : int, optional 

Number of rows in the matrix. A non-positive 

value means unknown, at which point the number 

of rows will be determined by the max row 

index plus one. 

numCols : int, optional 

Number of columns in the matrix. A non-positive 

value means unknown, at which point the number 

of columns will be determined by the max row 

index plus one. 

""" 

def __init__(self, entries, numRows=0, numCols=0): 

""" 

Note: This docstring is not shown publicly. 

 

Create a wrapper over a Java CoordinateMatrix. 

 

Publicly, we require that `rows` be an RDD. However, for 

internal usage, `rows` can also be a Java CoordinateMatrix 

object, in which case we can wrap it directly. This 

assists in clean matrix conversions. 

 

Examples 

-------- 

>>> entries = sc.parallelize([MatrixEntry(0, 0, 1.2), 

... MatrixEntry(6, 4, 2.1)]) 

>>> mat = CoordinateMatrix(entries) 

 

>>> mat_diff = CoordinateMatrix(entries) 

>>> (mat_diff._java_matrix_wrapper._java_model == 

... mat._java_matrix_wrapper._java_model) 

False 

 

>>> mat_same = CoordinateMatrix(mat._java_matrix_wrapper._java_model) 

>>> (mat_same._java_matrix_wrapper._java_model == 

... mat._java_matrix_wrapper._java_model) 

True 

""" 

if isinstance(entries, RDD): 

entries = entries.map(_convert_to_matrix_entry) 

# We use DataFrames for serialization of MatrixEntry entries 

# from Python, so first convert the RDD to a DataFrame on 

# this side. This will convert each MatrixEntry to a Row 

# containing the 'i', 'j', and 'value' values, which can 

# each be easily serialized. We will convert back to 

# MatrixEntry inputs on the Scala side. 

java_matrix = callMLlibFunc("createCoordinateMatrix", entries.toDF(), 

int(numRows), int(numCols)) 

950 ↛ 954line 950 didn't jump to line 954, because the condition on line 950 was never false elif (isinstance(entries, JavaObject) 

and entries.getClass().getSimpleName() == "CoordinateMatrix"): 

java_matrix = entries 

else: 

raise TypeError("entries should be an RDD of MatrixEntry entries or " 

"(int, int, float) tuples, got %s" % type(entries)) 

 

self._java_matrix_wrapper = JavaModelWrapper(java_matrix) 

 

@property 

def entries(self): 

""" 

Entries of the CoordinateMatrix stored as an RDD of 

MatrixEntries. 

 

Examples 

-------- 

>>> mat = CoordinateMatrix(sc.parallelize([MatrixEntry(0, 0, 1.2), 

... MatrixEntry(6, 4, 2.1)])) 

>>> entries = mat.entries 

>>> entries.first() 

MatrixEntry(0, 0, 1.2) 

""" 

# We use DataFrames for serialization of MatrixEntry entries 

# from Java, so we first convert the RDD of entries to a 

# DataFrame on the Scala/Java side. Then we map each Row in 

# the DataFrame back to a MatrixEntry on this side. 

entries_df = callMLlibFunc("getMatrixEntries", self._java_matrix_wrapper._java_model) 

entries = entries_df.rdd.map(lambda row: MatrixEntry(row[0], row[1], row[2])) 

return entries 

 

def numRows(self): 

""" 

Get or compute the number of rows. 

 

Examples 

-------- 

>>> entries = sc.parallelize([MatrixEntry(0, 0, 1.2), 

... MatrixEntry(1, 0, 2), 

... MatrixEntry(2, 1, 3.7)]) 

 

>>> mat = CoordinateMatrix(entries) 

>>> print(mat.numRows()) 

3 

 

>>> mat = CoordinateMatrix(entries, 7, 6) 

>>> print(mat.numRows()) 

7 

""" 

return self._java_matrix_wrapper.call("numRows") 

 

def numCols(self): 

""" 

Get or compute the number of cols. 

 

Examples 

-------- 

>>> entries = sc.parallelize([MatrixEntry(0, 0, 1.2), 

... MatrixEntry(1, 0, 2), 

... MatrixEntry(2, 1, 3.7)]) 

 

>>> mat = CoordinateMatrix(entries) 

>>> print(mat.numCols()) 

2 

 

>>> mat = CoordinateMatrix(entries, 7, 6) 

>>> print(mat.numCols()) 

6 

""" 

return self._java_matrix_wrapper.call("numCols") 

 

def transpose(self): 

""" 

Transpose this CoordinateMatrix. 

 

.. versionadded:: 2.0.0 

 

Examples 

-------- 

>>> entries = sc.parallelize([MatrixEntry(0, 0, 1.2), 

... MatrixEntry(1, 0, 2), 

... MatrixEntry(2, 1, 3.7)]) 

>>> mat = CoordinateMatrix(entries) 

>>> mat_transposed = mat.transpose() 

 

>>> print(mat_transposed.numRows()) 

2 

 

>>> print(mat_transposed.numCols()) 

3 

""" 

java_transposed_matrix = self._java_matrix_wrapper.call("transpose") 

return CoordinateMatrix(java_transposed_matrix) 

 

def toRowMatrix(self): 

""" 

Convert this matrix to a RowMatrix. 

 

Examples 

-------- 

>>> entries = sc.parallelize([MatrixEntry(0, 0, 1.2), 

... MatrixEntry(6, 4, 2.1)]) 

>>> mat = CoordinateMatrix(entries).toRowMatrix() 

 

>>> # This CoordinateMatrix will have 7 effective rows, due to 

>>> # the highest row index being 6, but the ensuing RowMatrix 

>>> # will only have 2 rows since there are only entries on 2 

>>> # unique rows. 

>>> print(mat.numRows()) 

2 

 

>>> # This CoordinateMatrix will have 5 columns, due to the 

>>> # highest column index being 4, and the ensuing RowMatrix 

>>> # will have 5 columns as well. 

>>> print(mat.numCols()) 

5 

""" 

java_row_matrix = self._java_matrix_wrapper.call("toRowMatrix") 

return RowMatrix(java_row_matrix) 

 

def toIndexedRowMatrix(self): 

""" 

Convert this matrix to an IndexedRowMatrix. 

 

Examples 

-------- 

>>> entries = sc.parallelize([MatrixEntry(0, 0, 1.2), 

... MatrixEntry(6, 4, 2.1)]) 

>>> mat = CoordinateMatrix(entries).toIndexedRowMatrix() 

 

>>> # This CoordinateMatrix will have 7 effective rows, due to 

>>> # the highest row index being 6, and the ensuing 

>>> # IndexedRowMatrix will have 7 rows as well. 

>>> print(mat.numRows()) 

7 

 

>>> # This CoordinateMatrix will have 5 columns, due to the 

>>> # highest column index being 4, and the ensuing 

>>> # IndexedRowMatrix will have 5 columns as well. 

>>> print(mat.numCols()) 

5 

""" 

java_indexed_row_matrix = self._java_matrix_wrapper.call("toIndexedRowMatrix") 

return IndexedRowMatrix(java_indexed_row_matrix) 

 

def toBlockMatrix(self, rowsPerBlock=1024, colsPerBlock=1024): 

""" 

Convert this matrix to a BlockMatrix. 

 

Parameters 

---------- 

rowsPerBlock : int, optional 

Number of rows that make up each block. 

The blocks forming the final rows are not 

required to have the given number of rows. 

colsPerBlock : int, optional 

Number of columns that make up each block. 

The blocks forming the final columns are not 

required to have the given number of columns. 

 

Examples 

-------- 

>>> entries = sc.parallelize([MatrixEntry(0, 0, 1.2), 

... MatrixEntry(6, 4, 2.1)]) 

>>> mat = CoordinateMatrix(entries).toBlockMatrix() 

 

>>> # This CoordinateMatrix will have 7 effective rows, due to 

>>> # the highest row index being 6, and the ensuing 

>>> # BlockMatrix will have 7 rows as well. 

>>> print(mat.numRows()) 

7 

 

>>> # This CoordinateMatrix will have 5 columns, due to the 

>>> # highest column index being 4, and the ensuing 

>>> # BlockMatrix will have 5 columns as well. 

>>> print(mat.numCols()) 

5 

""" 

java_block_matrix = self._java_matrix_wrapper.call("toBlockMatrix", 

rowsPerBlock, 

colsPerBlock) 

return BlockMatrix(java_block_matrix, rowsPerBlock, colsPerBlock) 

 

 

def _convert_to_matrix_block_tuple(block): 

if (isinstance(block, tuple) and len(block) == 2 

and isinstance(block[0], tuple) and len(block[0]) == 2 

and isinstance(block[1], Matrix)): 

blockRowIndex = int(block[0][0]) 

blockColIndex = int(block[0][1]) 

subMatrix = block[1] 

return ((blockRowIndex, blockColIndex), subMatrix) 

else: 

raise TypeError("Cannot convert type %s into a sub-matrix block tuple" % type(block)) 

 

 

class BlockMatrix(DistributedMatrix): 

""" 

Represents a distributed matrix in blocks of local matrices. 

 

Parameters 

---------- 

blocks : :py:class:`pyspark.RDD` 

An RDD of sub-matrix blocks 

((blockRowIndex, blockColIndex), sub-matrix) that 

form this distributed matrix. If multiple blocks 

with the same index exist, the results for 

operations like add and multiply will be 

unpredictable. 

rowsPerBlock : int 

Number of rows that make up each block. 

The blocks forming the final rows are not 

required to have the given number of rows. 

colsPerBlock : int 

Number of columns that make up each block. 

The blocks forming the final columns are not 

required to have the given number of columns. 

numRows : int, optional 

Number of rows of this matrix. If the supplied 

value is less than or equal to zero, the number 

of rows will be calculated when `numRows` is 

invoked. 

numCols : int, optional 

Number of columns of this matrix. If the supplied 

value is less than or equal to zero, the number 

of columns will be calculated when `numCols` is 

invoked. 

""" 

def __init__(self, blocks, rowsPerBlock, colsPerBlock, numRows=0, numCols=0): 

""" 

Note: This docstring is not shown publicly. 

 

Create a wrapper over a Java BlockMatrix. 

 

Publicly, we require that `blocks` be an RDD. However, for 

internal usage, `blocks` can also be a Java BlockMatrix 

object, in which case we can wrap it directly. This 

assists in clean matrix conversions. 

 

Examples 

-------- 

>>> blocks = sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])), 

... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]))]) 

>>> mat = BlockMatrix(blocks, 3, 2) 

 

>>> mat_diff = BlockMatrix(blocks, 3, 2) 

>>> (mat_diff._java_matrix_wrapper._java_model == 

... mat._java_matrix_wrapper._java_model) 

False 

 

>>> mat_same = BlockMatrix(mat._java_matrix_wrapper._java_model, 3, 2) 

>>> (mat_same._java_matrix_wrapper._java_model == 

... mat._java_matrix_wrapper._java_model) 

True 

""" 

if isinstance(blocks, RDD): 

blocks = blocks.map(_convert_to_matrix_block_tuple) 

# We use DataFrames for serialization of sub-matrix blocks 

# from Python, so first convert the RDD to a DataFrame on 

# this side. This will convert each sub-matrix block 

# tuple to a Row containing the 'blockRowIndex', 

# 'blockColIndex', and 'subMatrix' values, which can 

# each be easily serialized. We will convert back to 

# ((blockRowIndex, blockColIndex), sub-matrix) tuples on 

# the Scala side. 

java_matrix = callMLlibFunc("createBlockMatrix", blocks.toDF(), 

int(rowsPerBlock), int(colsPerBlock), 

int(numRows), int(numCols)) 

1218 ↛ 1222line 1218 didn't jump to line 1222, because the condition on line 1218 was never false elif (isinstance(blocks, JavaObject) 

and blocks.getClass().getSimpleName() == "BlockMatrix"): 

java_matrix = blocks 

else: 

raise TypeError("blocks should be an RDD of sub-matrix blocks as " 

"((int, int), matrix) tuples, got %s" % type(blocks)) 

 

self._java_matrix_wrapper = JavaModelWrapper(java_matrix) 

 

@property 

def blocks(self): 

""" 

The RDD of sub-matrix blocks 

((blockRowIndex, blockColIndex), sub-matrix) that form this 

distributed matrix. 

 

Examples 

-------- 

>>> mat = BlockMatrix( 

... sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])), 

... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]))]), 3, 2) 

>>> blocks = mat.blocks 

>>> blocks.first() 

((0, 0), DenseMatrix(3, 2, [1.0, 2.0, 3.0, 4.0, 5.0, 6.0], 0)) 

 

""" 

# We use DataFrames for serialization of sub-matrix blocks 

# from Java, so we first convert the RDD of blocks to a 

# DataFrame on the Scala/Java side. Then we map each Row in 

# the DataFrame back to a sub-matrix block on this side. 

blocks_df = callMLlibFunc("getMatrixBlocks", self._java_matrix_wrapper._java_model) 

blocks = blocks_df.rdd.map(lambda row: ((row[0][0], row[0][1]), row[1])) 

return blocks 

 

@property 

def rowsPerBlock(self): 

""" 

Number of rows that make up each block. 

 

Examples 

-------- 

>>> blocks = sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])), 

... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]))]) 

>>> mat = BlockMatrix(blocks, 3, 2) 

>>> mat.rowsPerBlock 

3 

""" 

return self._java_matrix_wrapper.call("rowsPerBlock") 

 

@property 

def colsPerBlock(self): 

""" 

Number of columns that make up each block. 

 

Examples 

-------- 

>>> blocks = sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])), 

... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]))]) 

>>> mat = BlockMatrix(blocks, 3, 2) 

>>> mat.colsPerBlock 

2 

""" 

return self._java_matrix_wrapper.call("colsPerBlock") 

 

@property 

def numRowBlocks(self): 

""" 

Number of rows of blocks in the BlockMatrix. 

 

Examples 

-------- 

>>> blocks = sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])), 

... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]))]) 

>>> mat = BlockMatrix(blocks, 3, 2) 

>>> mat.numRowBlocks 

2 

""" 

return self._java_matrix_wrapper.call("numRowBlocks") 

 

@property 

def numColBlocks(self): 

""" 

Number of columns of blocks in the BlockMatrix. 

 

Examples 

-------- 

>>> blocks = sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])), 

... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]))]) 

>>> mat = BlockMatrix(blocks, 3, 2) 

>>> mat.numColBlocks 

1 

""" 

return self._java_matrix_wrapper.call("numColBlocks") 

 

def numRows(self): 

""" 

Get or compute the number of rows. 

 

Examples 

-------- 

>>> blocks = sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])), 

... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]))]) 

 

>>> mat = BlockMatrix(blocks, 3, 2) 

>>> print(mat.numRows()) 

6 

 

>>> mat = BlockMatrix(blocks, 3, 2, 7, 6) 

>>> print(mat.numRows()) 

7 

""" 

return self._java_matrix_wrapper.call("numRows") 

 

def numCols(self): 

""" 

Get or compute the number of cols. 

 

Examples 

-------- 

>>> blocks = sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])), 

... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]))]) 

 

>>> mat = BlockMatrix(blocks, 3, 2) 

>>> print(mat.numCols()) 

2 

 

>>> mat = BlockMatrix(blocks, 3, 2, 7, 6) 

>>> print(mat.numCols()) 

6 

""" 

return self._java_matrix_wrapper.call("numCols") 

 

@since('2.0.0') 

def cache(self): 

""" 

Caches the underlying RDD. 

""" 

self._java_matrix_wrapper.call("cache") 

return self 

 

@since('2.0.0') 

def persist(self, storageLevel): 

""" 

Persists the underlying RDD with the specified storage level. 

""" 

if not isinstance(storageLevel, StorageLevel): 

raise TypeError("`storageLevel` should be a StorageLevel, got %s" % type(storageLevel)) 

javaStorageLevel = self._java_matrix_wrapper._sc._getJavaStorageLevel(storageLevel) 

self._java_matrix_wrapper.call("persist", javaStorageLevel) 

return self 

 

@since('2.0.0') 

def validate(self): 

""" 

Validates the block matrix info against the matrix data (`blocks`) 

and throws an exception if any error is found. 

""" 

self._java_matrix_wrapper.call("validate") 

 

def add(self, other): 

""" 

Adds two block matrices together. The matrices must have the 

same size and matching `rowsPerBlock` and `colsPerBlock` values. 

If one of the sub matrix blocks that are being added is a 

SparseMatrix, the resulting sub matrix block will also be a 

SparseMatrix, even if it is being added to a DenseMatrix. If 

two dense sub matrix blocks are added, the output block will 

also be a DenseMatrix. 

 

Examples 

-------- 

>>> dm1 = Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6]) 

>>> dm2 = Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]) 

>>> sm = Matrices.sparse(3, 2, [0, 1, 3], [0, 1, 2], [7, 11, 12]) 

>>> blocks1 = sc.parallelize([((0, 0), dm1), ((1, 0), dm2)]) 

>>> blocks2 = sc.parallelize([((0, 0), dm1), ((1, 0), dm2)]) 

>>> blocks3 = sc.parallelize([((0, 0), sm), ((1, 0), dm2)]) 

>>> mat1 = BlockMatrix(blocks1, 3, 2) 

>>> mat2 = BlockMatrix(blocks2, 3, 2) 

>>> mat3 = BlockMatrix(blocks3, 3, 2) 

 

>>> mat1.add(mat2).toLocalMatrix() 

DenseMatrix(6, 2, [2.0, 4.0, 6.0, 14.0, 16.0, 18.0, 8.0, 10.0, 12.0, 20.0, 22.0, 24.0], 0) 

 

>>> mat1.add(mat3).toLocalMatrix() 

DenseMatrix(6, 2, [8.0, 2.0, 3.0, 14.0, 16.0, 18.0, 4.0, 16.0, 18.0, 20.0, 22.0, 24.0], 0) 

""" 

1405 ↛ 1406line 1405 didn't jump to line 1406, because the condition on line 1405 was never true if not isinstance(other, BlockMatrix): 

raise TypeError("Other should be a BlockMatrix, got %s" % type(other)) 

 

other_java_block_matrix = other._java_matrix_wrapper._java_model 

java_block_matrix = self._java_matrix_wrapper.call("add", other_java_block_matrix) 

return BlockMatrix(java_block_matrix, self.rowsPerBlock, self.colsPerBlock) 

 

def subtract(self, other): 

""" 

Subtracts the given block matrix `other` from this block matrix: 

`this - other`. The matrices must have the same size and 

matching `rowsPerBlock` and `colsPerBlock` values. If one of 

the sub matrix blocks that are being subtracted is a 

SparseMatrix, the resulting sub matrix block will also be a 

SparseMatrix, even if it is being subtracted from a DenseMatrix. 

If two dense sub matrix blocks are subtracted, the output block 

will also be a DenseMatrix. 

 

.. versionadded:: 2.0.0 

 

Examples 

-------- 

>>> dm1 = Matrices.dense(3, 2, [3, 1, 5, 4, 6, 2]) 

>>> dm2 = Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]) 

>>> sm = Matrices.sparse(3, 2, [0, 1, 3], [0, 1, 2], [1, 2, 3]) 

>>> blocks1 = sc.parallelize([((0, 0), dm1), ((1, 0), dm2)]) 

>>> blocks2 = sc.parallelize([((0, 0), dm2), ((1, 0), dm1)]) 

>>> blocks3 = sc.parallelize([((0, 0), sm), ((1, 0), dm2)]) 

>>> mat1 = BlockMatrix(blocks1, 3, 2) 

>>> mat2 = BlockMatrix(blocks2, 3, 2) 

>>> mat3 = BlockMatrix(blocks3, 3, 2) 

 

>>> mat1.subtract(mat2).toLocalMatrix() 

DenseMatrix(6, 2, [-4.0, -7.0, -4.0, 4.0, 7.0, 4.0, -6.0, -5.0, -10.0, 6.0, 5.0, 10.0], 0) 

 

>>> mat2.subtract(mat3).toLocalMatrix() 

DenseMatrix(6, 2, [6.0, 8.0, 9.0, -4.0, -7.0, -4.0, 10.0, 9.0, 9.0, -6.0, -5.0, -10.0], 0) 

""" 

1443 ↛ 1444line 1443 didn't jump to line 1444, because the condition on line 1443 was never true if not isinstance(other, BlockMatrix): 

raise TypeError("Other should be a BlockMatrix, got %s" % type(other)) 

 

other_java_block_matrix = other._java_matrix_wrapper._java_model 

java_block_matrix = self._java_matrix_wrapper.call("subtract", other_java_block_matrix) 

return BlockMatrix(java_block_matrix, self.rowsPerBlock, self.colsPerBlock) 

 

def multiply(self, other): 

""" 

Left multiplies this BlockMatrix by `other`, another 

BlockMatrix. The `colsPerBlock` of this matrix must equal the 

`rowsPerBlock` of `other`. If `other` contains any SparseMatrix 

blocks, they will have to be converted to DenseMatrix blocks. 

The output BlockMatrix will only consist of DenseMatrix blocks. 

This may cause some performance issues until support for 

multiplying two sparse matrices is added. 

 

Examples 

-------- 

>>> dm1 = Matrices.dense(2, 3, [1, 2, 3, 4, 5, 6]) 

>>> dm2 = Matrices.dense(2, 3, [7, 8, 9, 10, 11, 12]) 

>>> dm3 = Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6]) 

>>> dm4 = Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]) 

>>> sm = Matrices.sparse(3, 2, [0, 1, 3], [0, 1, 2], [7, 11, 12]) 

>>> blocks1 = sc.parallelize([((0, 0), dm1), ((0, 1), dm2)]) 

>>> blocks2 = sc.parallelize([((0, 0), dm3), ((1, 0), dm4)]) 

>>> blocks3 = sc.parallelize([((0, 0), sm), ((1, 0), dm4)]) 

>>> mat1 = BlockMatrix(blocks1, 2, 3) 

>>> mat2 = BlockMatrix(blocks2, 3, 2) 

>>> mat3 = BlockMatrix(blocks3, 3, 2) 

 

>>> mat1.multiply(mat2).toLocalMatrix() 

DenseMatrix(2, 2, [242.0, 272.0, 350.0, 398.0], 0) 

 

>>> mat1.multiply(mat3).toLocalMatrix() 

DenseMatrix(2, 2, [227.0, 258.0, 394.0, 450.0], 0) 

""" 

1480 ↛ 1481line 1480 didn't jump to line 1481, because the condition on line 1480 was never true if not isinstance(other, BlockMatrix): 

raise TypeError("Other should be a BlockMatrix, got %s" % type(other)) 

 

other_java_block_matrix = other._java_matrix_wrapper._java_model 

java_block_matrix = self._java_matrix_wrapper.call("multiply", other_java_block_matrix) 

return BlockMatrix(java_block_matrix, self.rowsPerBlock, self.colsPerBlock) 

 

def transpose(self): 

""" 

Transpose this BlockMatrix. Returns a new BlockMatrix 

instance sharing the same underlying data. Is a lazy operation. 

 

.. versionadded:: 2.0.0 

 

Examples 

-------- 

>>> blocks = sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])), 

... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]))]) 

>>> mat = BlockMatrix(blocks, 3, 2) 

 

>>> mat_transposed = mat.transpose() 

>>> mat_transposed.toLocalMatrix() 

DenseMatrix(2, 6, [1.0, 4.0, 2.0, 5.0, 3.0, 6.0, 7.0, 10.0, 8.0, 11.0, 9.0, 12.0], 0) 

""" 

java_transposed_matrix = self._java_matrix_wrapper.call("transpose") 

return BlockMatrix(java_transposed_matrix, self.colsPerBlock, self.rowsPerBlock) 

 

def toLocalMatrix(self): 

""" 

Collect the distributed matrix on the driver as a DenseMatrix. 

 

Examples 

-------- 

>>> blocks = sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])), 

... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]))]) 

>>> mat = BlockMatrix(blocks, 3, 2).toLocalMatrix() 

 

>>> # This BlockMatrix will have 6 effective rows, due to 

>>> # having two sub-matrix blocks stacked, each with 3 rows. 

>>> # The ensuing DenseMatrix will also have 6 rows. 

>>> print(mat.numRows) 

6 

 

>>> # This BlockMatrix will have 2 effective columns, due to 

>>> # having two sub-matrix blocks stacked, each with 2 

>>> # columns. The ensuing DenseMatrix will also have 2 columns. 

>>> print(mat.numCols) 

2 

""" 

return self._java_matrix_wrapper.call("toLocalMatrix") 

 

def toIndexedRowMatrix(self): 

""" 

Convert this matrix to an IndexedRowMatrix. 

 

Examples 

-------- 

>>> blocks = sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])), 

... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]))]) 

>>> mat = BlockMatrix(blocks, 3, 2).toIndexedRowMatrix() 

 

>>> # This BlockMatrix will have 6 effective rows, due to 

>>> # having two sub-matrix blocks stacked, each with 3 rows. 

>>> # The ensuing IndexedRowMatrix will also have 6 rows. 

>>> print(mat.numRows()) 

6 

 

>>> # This BlockMatrix will have 2 effective columns, due to 

>>> # having two sub-matrix blocks stacked, each with 2 columns. 

>>> # The ensuing IndexedRowMatrix will also have 2 columns. 

>>> print(mat.numCols()) 

2 

""" 

java_indexed_row_matrix = self._java_matrix_wrapper.call("toIndexedRowMatrix") 

return IndexedRowMatrix(java_indexed_row_matrix) 

 

def toCoordinateMatrix(self): 

""" 

Convert this matrix to a CoordinateMatrix. 

 

Examples 

-------- 

>>> blocks = sc.parallelize([((0, 0), Matrices.dense(1, 2, [1, 2])), 

... ((1, 0), Matrices.dense(1, 2, [7, 8]))]) 

>>> mat = BlockMatrix(blocks, 1, 2).toCoordinateMatrix() 

>>> mat.entries.take(3) 

[MatrixEntry(0, 0, 1.0), MatrixEntry(0, 1, 2.0), MatrixEntry(1, 0, 7.0)] 

""" 

java_coordinate_matrix = self._java_matrix_wrapper.call("toCoordinateMatrix") 

return CoordinateMatrix(java_coordinate_matrix) 

 

 

def _test(): 

import doctest 

import numpy 

from pyspark.sql import SparkSession 

from pyspark.mllib.linalg import Matrices 

import pyspark.mllib.linalg.distributed 

try: 

# Numpy 1.14+ changed it's string format. 

numpy.set_printoptions(legacy='1.13') 

except TypeError: 

pass 

globs = pyspark.mllib.linalg.distributed.__dict__.copy() 

spark = SparkSession.builder\ 

.master("local[2]")\ 

.appName("mllib.linalg.distributed tests")\ 

.getOrCreate() 

globs['sc'] = spark.sparkContext 

globs['Matrices'] = Matrices 

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

spark.stop() 

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

sys.exit(-1) 

 

if __name__ == "__main__": 

_test()