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

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

1887

1888

1889

1890

1891

1892

1893

1894

1895

1896

1897

1898

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

1909

1910

1911

1912

1913

1914

1915

1916

1917

1918

1919

1920

1921

1922

1923

1924

1925

1926

1927

1928

1929

1930

1931

1932

1933

1934

1935

1936

1937

1938

1939

1940

1941

1942

1943

1944

1945

1946

1947

1948

1949

1950

1951

1952

1953

1954

1955

1956

1957

1958

1959

1960

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

2055

2056

2057

2058

2059

2060

2061

2062

2063

2064

2065

2066

2067

2068

2069

2070

2071

2072

2073

2074

2075

2076

2077

2078

2079

2080

2081

2082

2083

2084

2085

2086

2087

2088

2089

2090

2091

2092

2093

2094

2095

2096

2097

2098

2099

2100

2101

2102

2103

2104

2105

2106

2107

2108

2109

2110

2111

2112

2113

2114

2115

2116

2117

2118

2119

2120

2121

2122

2123

2124

2125

2126

2127

2128

2129

2130

2131

2132

2133

2134

2135

2136

2137

2138

2139

2140

2141

2142

2143

2144

2145

2146

2147

2148

2149

2150

2151

2152

2153

2154

2155

2156

2157

2158

2159

2160

2161

2162

2163

2164

2165

2166

2167

2168

2169

2170

2171

2172

2173

2174

2175

2176

2177

2178

2179

2180

2181

2182

2183

2184

2185

2186

2187

2188

2189

2190

2191

2192

2193

2194

2195

2196

2197

2198

2199

2200

2201

2202

2203

2204

2205

2206

2207

2208

2209

2210

2211

2212

2213

2214

2215

2216

2217

2218

2219

2220

2221

2222

2223

2224

2225

2226

2227

2228

2229

2230

2231

2232

2233

2234

2235

2236

2237

2238

2239

2240

2241

2242

2243

2244

2245

2246

2247

2248

2249

2250

2251

2252

2253

2254

2255

2256

2257

2258

2259

2260

2261

2262

2263

2264

2265

2266

2267

2268

2269

2270

2271

2272

2273

2274

2275

2276

2277

2278

2279

2280

2281

2282

2283

2284

2285

2286

2287

2288

2289

2290

2291

2292

2293

2294

2295

2296

2297

2298

2299

2300

2301

2302

2303

2304

2305

2306

2307

2308

2309

2310

2311

2312

2313

2314

2315

2316

2317

2318

2319

2320

2321

2322

2323

2324

2325

2326

2327

2328

2329

2330

2331

2332

2333

2334

2335

2336

2337

2338

2339

2340

2341

2342

2343

2344

2345

2346

2347

2348

2349

2350

2351

2352

2353

2354

2355

2356

2357

2358

2359

2360

2361

2362

2363

2364

2365

2366

2367

2368

2369

2370

2371

2372

2373

2374

2375

2376

2377

2378

2379

2380

2381

2382

2383

2384

2385

2386

2387

2388

2389

2390

2391

2392

2393

2394

2395

2396

2397

2398

2399

2400

2401

2402

2403

2404

2405

2406

2407

2408

2409

2410

2411

2412

2413

2414

2415

2416

2417

2418

2419

2420

2421

2422

2423

2424

2425

2426

2427

2428

2429

2430

2431

2432

2433

2434

2435

2436

2437

2438

2439

2440

2441

2442

2443

2444

2445

2446

2447

2448

2449

2450

2451

2452

2453

2454

2455

2456

2457

2458

2459

2460

2461

2462

2463

2464

2465

2466

2467

2468

2469

2470

2471

2472

2473

2474

2475

2476

2477

2478

2479

2480

2481

2482

2483

2484

2485

2486

2487

2488

2489

2490

2491

2492

2493

2494

2495

2496

2497

2498

2499

2500

2501

2502

2503

2504

2505

2506

2507

2508

2509

2510

2511

2512

2513

2514

2515

2516

2517

2518

2519

2520

2521

2522

2523

2524

2525

2526

2527

2528

2529

2530

2531

2532

2533

2534

2535

2536

2537

2538

2539

2540

2541

2542

2543

2544

2545

2546

2547

2548

2549

2550

2551

2552

2553

2554

2555

2556

2557

2558

2559

2560

2561

2562

2563

2564

2565

2566

2567

2568

2569

2570

2571

2572

2573

2574

2575

2576

2577

2578

2579

2580

2581

2582

2583

2584

2585

2586

2587

2588

2589

2590

2591

2592

2593

2594

2595

2596

2597

2598

2599

2600

2601

2602

2603

2604

2605

2606

2607

2608

2609

2610

2611

2612

2613

2614

2615

2616

2617

2618

2619

2620

2621

2622

2623

2624

2625

2626

2627

2628

2629

2630

2631

2632

2633

2634

2635

2636

2637

2638

2639

2640

2641

2642

2643

2644

2645

2646

2647

2648

2649

2650

2651

2652

2653

2654

2655

2656

2657

2658

2659

2660

2661

2662

2663

2664

2665

2666

2667

2668

2669

2670

2671

2672

2673

2674

2675

2676

2677

2678

2679

2680

2681

2682

2683

2684

2685

2686

2687

2688

2689

2690

2691

2692

2693

2694

2695

2696

2697

2698

2699

2700

2701

2702

2703

2704

2705

2706

2707

2708

2709

2710

2711

2712

2713

2714

2715

2716

2717

2718

2719

2720

2721

2722

2723

2724

2725

2726

2727

2728

2729

2730

2731

2732

2733

2734

2735

2736

2737

2738

2739

2740

2741

2742

2743

2744

2745

2746

2747

2748

2749

2750

2751

2752

2753

2754

2755

2756

2757

2758

2759

2760

2761

2762

2763

2764

2765

2766

2767

2768

2769

2770

2771

2772

2773

2774

2775

2776

2777

2778

2779

2780

2781

2782

2783

2784

2785

2786

2787

2788

2789

2790

2791

2792

2793

2794

2795

2796

2797

2798

2799

2800

2801

2802

2803

2804

2805

2806

2807

2808

2809

2810

2811

2812

2813

2814

2815

2816

2817

2818

2819

2820

2821

2822

2823

2824

2825

2826

2827

2828

2829

2830

2831

2832

2833

2834

2835

2836

2837

2838

2839

2840

2841

2842

2843

2844

2845

2846

2847

2848

2849

2850

2851

2852

2853

2854

2855

2856

2857

2858

2859

2860

2861

2862

2863

2864

2865

2866

2867

2868

2869

2870

2871

2872

2873

2874

2875

2876

2877

2878

2879

2880

2881

2882

2883

2884

2885

2886

2887

2888

2889

2890

2891

2892

2893

2894

2895

2896

2897

2898

2899

2900

2901

2902

2903

2904

2905

2906

2907

2908

2909

2910

2911

2912

2913

2914

2915

2916

2917

2918

2919

2920

2921

2922

2923

2924

2925

2926

2927

2928

2929

2930

2931

2932

2933

2934

2935

2936

2937

2938

2939

2940

2941

2942

2943

2944

2945

2946

2947

2948

2949

2950

2951

2952

2953

2954

2955

2956

2957

2958

2959

2960

2961

2962

2963

2964

2965

2966

2967

2968

2969

2970

2971

2972

2973

2974

2975

2976

2977

2978

2979

2980

2981

2982

2983

2984

2985

2986

2987

2988

2989

2990

2991

2992

2993

2994

2995

2996

2997

2998

2999

3000

3001

3002

3003

3004

3005

3006

3007

3008

3009

3010

3011

3012

3013

3014

3015

3016

3017

3018

3019

3020

3021

3022

3023

3024

3025

3026

3027

3028

3029

3030

3031

3032

3033

3034

3035

3036

3037

3038

3039

3040

3041

3042

3043

3044

3045

3046

3047

3048

3049

3050

3051

3052

3053

3054

3055

3056

3057

3058

3059

3060

3061

3062

3063

3064

3065

3066

3067

3068

3069

3070

3071

3072

3073

3074

3075

3076

3077

3078

3079

3080

3081

3082

3083

3084

3085

3086

3087

3088

3089

3090

3091

3092

3093

3094

3095

3096

3097

3098

3099

3100

3101

3102

3103

3104

3105

3106

3107

3108

3109

3110

3111

3112

3113

3114

3115

3116

3117

3118

3119

3120

3121

3122

3123

3124

3125

3126

3127

3128

3129

3130

3131

3132

3133

3134

3135

3136

3137

3138

3139

3140

3141

3142

3143

3144

3145

3146

3147

3148

3149

3150

3151

3152

3153

3154

3155

3156

3157

3158

3159

3160

3161

3162

3163

3164

3165

3166

3167

3168

3169

3170

3171

3172

3173

3174

3175

3176

3177

3178

3179

3180

3181

3182

3183

3184

3185

3186

3187

3188

3189

3190

3191

3192

3193

3194

3195

3196

3197

3198

3199

3200

3201

3202

3203

3204

3205

3206

3207

3208

3209

3210

3211

3212

3213

3214

3215

3216

3217

3218

3219

3220

3221

3222

3223

3224

3225

3226

3227

3228

3229

3230

3231

3232

3233

3234

3235

3236

3237

3238

3239

3240

3241

3242

3243

3244

3245

3246

3247

3248

3249

3250

3251

3252

3253

3254

3255

3256

3257

3258

3259

3260

3261

3262

3263

3264

3265

3266

3267

3268

3269

3270

3271

3272

3273

3274

3275

3276

3277

3278

3279

3280

3281

3282

3283

3284

3285

3286

3287

3288

3289

3290

3291

3292

3293

3294

3295

3296

3297

3298

3299

3300

3301

3302

3303

3304

3305

3306

3307

3308

3309

3310

3311

3312

3313

3314

3315

3316

3317

3318

3319

3320

3321

3322

3323

3324

3325

3326

3327

3328

3329

3330

3331

3332

3333

3334

3335

3336

3337

3338

3339

3340

3341

3342

3343

3344

3345

3346

3347

3348

3349

3350

3351

3352

3353

3354

3355

3356

3357

3358

3359

3360

3361

3362

3363

3364

3365

3366

3367

3368

3369

3370

3371

3372

3373

3374

3375

3376

3377

3378

3379

3380

3381

3382

3383

3384

3385

3386

3387

3388

3389

3390

3391

3392

3393

3394

3395

3396

3397

3398

3399

3400

3401

3402

3403

3404

3405

3406

3407

3408

3409

3410

3411

3412

3413

3414

3415

3416

3417

3418

3419

3420

3421

3422

3423

3424

3425

3426

3427

3428

3429

3430

3431

3432

3433

3434

3435

3436

3437

3438

3439

3440

3441

3442

3443

3444

3445

3446

3447

3448

3449

3450

3451

3452

3453

3454

3455

3456

3457

3458

3459

3460

3461

3462

3463

3464

3465

3466

3467

3468

3469

3470

3471

3472

3473

3474

3475

3476

3477

3478

3479

3480

3481

3482

3483

3484

3485

3486

3487

3488

3489

3490

3491

3492

3493

3494

3495

3496

3497

3498

3499

3500

3501

3502

3503

3504

3505

3506

3507

3508

3509

3510

3511

3512

3513

3514

3515

3516

3517

3518

3519

3520

3521

3522

3523

3524

3525

3526

3527

3528

3529

3530

3531

3532

3533

3534

3535

3536

3537

3538

3539

3540

3541

3542

3543

3544

3545

3546

3547

3548

3549

3550

3551

3552

3553

3554

3555

3556

3557

3558

3559

3560

3561

3562

3563

3564

3565

3566

3567

3568

3569

3570

3571

3572

3573

3574

3575

3576

3577

3578

3579

3580

3581

3582

3583

3584

3585

3586

3587

3588

3589

3590

3591

3592

3593

3594

3595

3596

3597

3598

3599

3600

3601

3602

3603

3604

3605

3606

3607

3608

3609

3610

3611

3612

3613

3614

3615

3616

3617

3618

3619

3620

3621

3622

3623

3624

3625

3626

3627

3628

3629

3630

3631

3632

3633

3634

3635

3636

3637

3638

3639

3640

3641

3642

3643

3644

3645

3646

3647

3648

3649

3650

3651

3652

3653

3654

3655

3656

3657

3658

3659

3660

3661

3662

3663

3664

3665

3666

3667

3668

3669

3670

3671

3672

3673

3674

3675

3676

3677

3678

3679

3680

3681

3682

3683

3684

3685

3686

3687

3688

3689

3690

3691

3692

3693

3694

3695

3696

3697

3698

3699

3700

3701

3702

3703

3704

3705

3706

3707

3708

3709

3710

3711

3712

3713

3714

3715

3716

3717

3718

3719

3720

3721

3722

3723

3724

3725

3726

3727

3728

3729

3730

3731

3732

3733

3734

3735

3736

3737

3738

3739

3740

3741

3742

3743

3744

3745

3746

3747

3748

3749

3750

3751

3752

3753

3754

3755

3756

3757

3758

3759

3760

3761

3762

3763

3764

3765

3766

3767

3768

3769

3770

3771

3772

3773

3774

3775

3776

3777

3778

3779

3780

3781

3782

3783

3784

3785

3786

3787

3788

3789

3790

3791

3792

3793

3794

3795

3796

3797

3798

3799

3800

3801

3802

3803

3804

3805

3806

3807

3808

3809

3810

3811

3812

3813

3814

3815

3816

3817

3818

3819

3820

3821

3822

3823

3824

3825

3826

3827

3828

3829

3830

3831

3832

3833

3834

3835

3836

3837

3838

3839

3840

3841

3842

3843

3844

3845

3846

3847

3848

3849

3850

3851

3852

3853

3854

3855

3856

3857

3858

3859

3860

3861

3862

3863

3864

3865

3866

3867

3868

3869

3870

3871

3872

3873

3874

3875

3876

3877

3878

3879

3880

3881

3882

3883

3884

3885

3886

3887

3888

3889

3890

3891

3892

3893

3894

3895

3896

3897

3898

3899

3900

3901

3902

3903

3904

3905

3906

3907

3908

3909

3910

3911

3912

3913

3914

3915

3916

3917

3918

3919

3920

3921

3922

3923

3924

3925

3926

3927

3928

3929

3930

3931

3932

3933

3934

3935

3936

3937

3938

3939

3940

3941

3942

3943

3944

3945

3946

3947

3948

3949

3950

3951

3952

3953

3954

3955

3956

3957

3958

3959

3960

3961

3962

3963

3964

3965

3966

3967

3968

3969

3970

3971

3972

3973

3974

3975

3976

3977

3978

3979

3980

3981

3982

3983

3984

3985

3986

3987

3988

3989

3990

3991

3992

3993

3994

3995

3996

3997

3998

3999

4000

4001

4002

4003

4004

4005

4006

4007

4008

4009

4010

4011

4012

4013

4014

4015

4016

4017

4018

4019

4020

4021

4022

4023

4024

4025

4026

4027

4028

4029

4030

4031

4032

4033

4034

4035

4036

4037

4038

4039

4040

4041

4042

4043

4044

4045

4046

4047

4048

4049

4050

4051

4052

4053

4054

4055

4056

4057

4058

4059

4060

4061

4062

4063

4064

4065

4066

4067

4068

4069

4070

4071

4072

4073

4074

4075

4076

4077

4078

4079

4080

4081

4082

4083

4084

4085

4086

4087

4088

4089

4090

4091

4092

4093

4094

4095

4096

4097

4098

4099

4100

4101

4102

4103

4104

4105

4106

4107

4108

4109

4110

4111

4112

4113

4114

4115

4116

4117

4118

4119

4120

4121

4122

4123

4124

4125

4126

4127

4128

4129

4130

4131

4132

4133

4134

4135

4136

4137

4138

4139

4140

4141

4142

4143

4144

4145

4146

4147

4148

4149

4150

4151

4152

4153

4154

4155

4156

4157

4158

4159

4160

4161

4162

4163

4164

4165

4166

4167

4168

4169

4170

4171

4172

4173

4174

4175

4176

4177

4178

4179

4180

4181

4182

4183

4184

4185

4186

4187

4188

4189

4190

4191

4192

4193

4194

4195

4196

4197

4198

4199

4200

4201

4202

4203

4204

4205

4206

4207

4208

4209

4210

4211

4212

4213

4214

4215

4216

4217

4218

4219

4220

4221

4222

4223

4224

4225

4226

4227

4228

4229

4230

4231

4232

4233

4234

4235

4236

4237

4238

4239

4240

4241

4242

4243

4244

4245

4246

4247

4248

4249

4250

4251

4252

4253

4254

4255

4256

4257

4258

4259

4260

4261

4262

4263

4264

4265

4266

4267

4268

4269

4270

4271

4272

4273

4274

4275

4276

4277

4278

4279

4280

4281

4282

4283

4284

4285

4286

4287

4288

4289

4290

4291

4292

4293

4294

4295

4296

4297

4298

4299

4300

4301

4302

4303

4304

4305

4306

4307

4308

4309

4310

4311

4312

4313

4314

4315

4316

4317

4318

4319

4320

4321

4322

4323

4324

4325

4326

4327

4328

4329

4330

4331

4332

4333

4334

4335

4336

4337

4338

4339

4340

4341

4342

4343

4344

4345

4346

4347

4348

4349

4350

4351

4352

4353

4354

4355

4356

4357

4358

4359

4360

4361

4362

4363

4364

4365

4366

4367

4368

4369

4370

4371

4372

4373

4374

4375

4376

4377

4378

4379

4380

4381

4382

4383

4384

4385

4386

4387

4388

4389

4390

4391

4392

4393

4394

4395

4396

4397

4398

4399

4400

4401

4402

4403

4404

4405

4406

4407

4408

4409

4410

4411

4412

4413

4414

4415

4416

4417

4418

4419

4420

4421

4422

4423

4424

4425

4426

4427

4428

4429

4430

4431

4432

4433

4434

4435

4436

4437

4438

4439

4440

4441

4442

4443

4444

4445

4446

4447

4448

4449

4450

4451

4452

4453

4454

4455

4456

4457

4458

4459

4460

4461

4462

4463

4464

4465

4466

4467

4468

4469

4470

4471

4472

4473

4474

4475

4476

4477

4478

4479

4480

4481

4482

4483

4484

4485

4486

4487

4488

4489

4490

4491

4492

4493

4494

4495

4496

4497

4498

4499

4500

4501

4502

4503

4504

4505

4506

4507

4508

4509

4510

4511

4512

4513

4514

4515

4516

4517

4518

4519

4520

4521

4522

4523

4524

4525

4526

4527

4528

4529

4530

4531

4532

4533

4534

4535

4536

4537

4538

4539

4540

4541

4542

4543

4544

4545

4546

4547

4548

4549

4550

4551

4552

4553

4554

4555

4556

4557

4558

4559

4560

4561

4562

4563

4564

4565

4566

4567

4568

4569

4570

4571

4572

4573

4574

4575

4576

4577

4578

4579

4580

4581

4582

4583

4584

4585

4586

4587

4588

4589

4590

4591

4592

4593

4594

4595

4596

4597

4598

4599

4600

4601

4602

4603

4604

4605

4606

4607

4608

4609

4610

4611

4612

4613

4614

4615

4616

4617

4618

4619

4620

4621

4622

4623

4624

4625

4626

4627

4628

4629

4630

4631

4632

4633

4634

4635

4636

4637

4638

4639

4640

4641

4642

4643

4644

4645

4646

4647

4648

4649

4650

4651

4652

4653

4654

4655

4656

4657

4658

4659

4660

4661

4662

4663

4664

4665

4666

4667

4668

4669

4670

4671

4672

4673

4674

4675

4676

4677

4678

4679

4680

4681

4682

4683

4684

4685

4686

4687

4688

4689

4690

4691

4692

4693

4694

4695

4696

4697

4698

4699

4700

4701

4702

4703

4704

4705

4706

4707

4708

4709

4710

4711

4712

4713

4714

4715

4716

4717

4718

4719

4720

4721

4722

4723

4724

4725

4726

4727

4728

4729

4730

4731

4732

4733

4734

4735

4736

4737

4738

4739

4740

4741

4742

4743

4744

4745

4746

4747

4748

4749

4750

4751

4752

4753

4754

4755

4756

4757

4758

4759

4760

4761

4762

4763

4764

4765

4766

4767

4768

4769

4770

4771

4772

4773

4774

4775

4776

4777

4778

4779

4780

4781

4782

4783

4784

4785

4786

4787

4788

4789

4790

4791

4792

4793

4794

4795

4796

4797

4798

4799

4800

4801

4802

4803

4804

4805

4806

4807

4808

4809

4810

4811

4812

4813

4814

4815

4816

4817

4818

4819

4820

4821

4822

4823

4824

4825

4826

4827

4828

4829

4830

4831

4832

4833

4834

4835

4836

4837

4838

4839

4840

4841

4842

4843

4844

4845

4846

4847

4848

4849

4850

4851

4852

4853

4854

4855

4856

4857

4858

4859

4860

4861

4862

4863

4864

4865

4866

4867

4868

4869

4870

4871

4872

4873

4874

4875

4876

4877

4878

4879

4880

4881

4882

4883

4884

4885

4886

4887

4888

4889

4890

4891

4892

4893

4894

4895

4896

4897

4898

4899

4900

4901

4902

4903

4904

4905

4906

4907

4908

4909

4910

4911

4912

4913

4914

4915

4916

4917

4918

4919

4920

4921

4922

4923

4924

4925

4926

4927

4928

4929

4930

4931

4932

4933

4934

4935

4936

4937

4938

4939

4940

4941

4942

4943

4944

4945

4946

4947

4948

4949

4950

4951

4952

4953

4954

4955

4956

4957

4958

4959

4960

4961

4962

4963

4964

4965

4966

4967

4968

4969

4970

4971

4972

4973

4974

4975

4976

4977

4978

4979

4980

4981

4982

4983

4984

4985

4986

4987

4988

4989

4990

4991

4992

4993

4994

4995

4996

4997

4998

4999

5000

5001

5002

5003

5004

5005

5006

5007

5008

5009

5010

5011

5012

5013

5014

5015

5016

5017

5018

5019

5020

5021

5022

5023

5024

5025

5026

5027

5028

5029

5030

5031

5032

5033

5034

5035

5036

5037

5038

5039

5040

5041

5042

5043

5044

5045

5046

5047

5048

5049

5050

5051

5052

5053

5054

5055

5056

5057

5058

5059

5060

5061

5062

5063

5064

5065

5066

5067

5068

5069

5070

5071

5072

5073

5074

5075

5076

5077

5078

5079

5080

5081

5082

5083

5084

5085

5086

5087

5088

5089

5090

5091

5092

5093

5094

5095

5096

5097

5098

5099

5100

5101

5102

5103

5104

5105

5106

5107

5108

5109

5110

5111

5112

5113

5114

5115

5116

5117

5118

5119

5120

5121

5122

5123

5124

5125

5126

5127

5128

5129

5130

5131

5132

5133

5134

5135

5136

5137

5138

5139

5140

5141

5142

5143

5144

5145

5146

5147

5148

5149

5150

5151

5152

5153

5154

5155

5156

5157

5158

5159

5160

5161

5162

5163

5164

5165

5166

5167

5168

5169

5170

5171

5172

5173

5174

5175

5176

5177

5178

5179

5180

5181

5182

5183

5184

5185

5186

5187

5188

5189

5190

5191

5192

5193

5194

5195

5196

5197

5198

5199

5200

5201

5202

5203

5204

5205

5206

5207

5208

5209

5210

5211

5212

5213

5214

5215

5216

5217

5218

5219

5220

5221

5222

5223

5224

5225

5226

5227

5228

5229

5230

5231

5232

5233

5234

5235

5236

5237

5238

5239

5240

5241

5242

5243

5244

5245

5246

5247

5248

5249

5250

5251

5252

5253

5254

5255

5256

5257

5258

5259

5260

5261

5262

5263

5264

5265

5266

5267

5268

5269

5270

5271

5272

5273

5274

5275

5276

5277

5278

5279

5280

5281

5282

5283

5284

5285

5286

5287

5288

5289

5290

5291

5292

5293

5294

5295

5296

5297

5298

5299

5300

5301

5302

5303

5304

5305

5306

5307

5308

5309

5310

5311

5312

5313

5314

5315

5316

5317

5318

5319

5320

5321

5322

5323

5324

5325

5326

5327

5328

5329

5330

5331

5332

5333

5334

5335

5336

5337

5338

5339

5340

5341

5342

5343

5344

5345

5346

5347

5348

5349

5350

5351

5352

5353

5354

5355

5356

5357

5358

5359

5360

5361

5362

5363

5364

5365

5366

5367

5368

5369

5370

5371

5372

5373

5374

5375

5376

5377

5378

5379

5380

5381

5382

5383

5384

5385

5386

5387

5388

5389

5390

5391

5392

5393

5394

5395

5396

5397

5398

5399

5400

5401

5402

5403

5404

5405

5406

5407

5408

5409

5410

5411

5412

5413

5414

5415

5416

5417

5418

5419

5420

5421

5422

5423

5424

5425

5426

5427

5428

5429

5430

5431

5432

5433

5434

5435

5436

5437

5438

5439

5440

5441

5442

5443

5444

5445

5446

5447

5448

5449

5450

5451

5452

5453

5454

5455

5456

5457

5458

5459

5460

5461

5462

5463

5464

5465

5466

5467

5468

5469

5470

5471

5472

5473

5474

5475

5476

5477

5478

5479

5480

5481

5482

5483

5484

5485

5486

5487

5488

5489

5490

5491

5492

5493

5494

5495

5496

5497

5498

5499

5500

5501

5502

5503

5504

5505

5506

5507

5508

5509

5510

5511

5512

5513

5514

5515

5516

5517

5518

5519

5520

5521

5522

5523

5524

5525

5526

5527

5528

5529

5530

5531

5532

5533

5534

5535

5536

5537

5538

5539

5540

5541

5542

5543

5544

5545

5546

5547

5548

5549

5550

5551

5552

5553

5554

5555

5556

5557

5558

5559

5560

5561

5562

5563

5564

5565

5566

5567

5568

5569

5570

5571

5572

5573

5574

5575

5576

5577

5578

5579

5580

5581

5582

5583

5584

5585

5586

5587

5588

5589

5590

5591

5592

5593

5594

5595

5596

5597

5598

5599

5600

5601

5602

5603

5604

5605

5606

5607

5608

5609

5610

5611

5612

5613

5614

5615

5616

5617

5618

5619

5620

5621

5622

5623

5624

5625

5626

5627

5628

5629

5630

5631

5632

5633

5634

5635

5636

5637

5638

5639

5640

5641

5642

5643

5644

5645

5646

5647

5648

5649

5650

5651

5652

5653

5654

5655

5656

5657

5658

5659

5660

5661

5662

5663

5664

5665

5666

5667

5668

5669

5670

5671

5672

5673

5674

5675

5676

5677

5678

5679

5680

5681

5682

5683

5684

5685

5686

5687

5688

5689

5690

5691

5692

5693

5694

5695

5696

5697

5698

5699

5700

5701

5702

5703

5704

5705

5706

5707

5708

5709

5710

5711

5712

5713

5714

5715

5716

5717

5718

5719

5720

5721

5722

5723

5724

5725

5726

5727

5728

5729

5730

5731

5732

5733

5734

5735

5736

5737

5738

5739

5740

5741

5742

5743

5744

5745

5746

5747

5748

5749

5750

5751

5752

5753

5754

5755

5756

5757

5758

5759

5760

5761

5762

5763

5764

5765

5766

5767

5768

5769

5770

5771

5772

5773

5774

5775

5776

5777

5778

5779

5780

5781

5782

5783

5784

5785

5786

5787

5788

5789

5790

5791

5792

5793

5794

5795

5796

5797

5798

5799

5800

5801

5802

5803

5804

5805

5806

5807

5808

5809

5810

5811

5812

5813

5814

5815

5816

5817

5818

5819

5820

5821

5822

5823

5824

5825

5826

5827

5828

5829

5830

5831

5832

5833

5834

5835

5836

5837

5838

5839

5840

5841

5842

5843

5844

5845

5846

5847

5848

5849

5850

5851

5852

5853

5854

5855

5856

5857

5858

5859

5860

5861

5862

5863

5864

5865

5866

5867

5868

5869

5870

5871

5872

5873

5874

5875

5876

5877

5878

5879

5880

5881

5882

5883

5884

5885

5886

5887

5888

5889

5890

5891

5892

5893

5894

5895

5896

5897

5898

5899

5900

5901

5902

5903

5904

5905

5906

5907

5908

5909

5910

5911

5912

5913

5914

5915

5916

5917

5918

5919

5920

5921

5922

5923

5924

5925

5926

5927

5928

5929

5930

5931

5932

5933

5934

5935

5936

5937

5938

5939

5940

5941

5942

5943

5944

5945

5946

5947

5948

5949

5950

5951

5952

5953

5954

5955

5956

5957

5958

5959

5960

5961

5962

5963

5964

5965

5966

5967

5968

5969

5970

5971

5972

5973

5974

5975

5976

5977

5978

5979

5980

5981

5982

5983

5984

5985

5986

5987

5988

5989

5990

5991

5992

5993

5994

5995

5996

5997

5998

5999

6000

6001

6002

6003

6004

6005

6006

6007

6008

6009

6010

6011

6012

6013

6014

6015

6016

6017

6018

6019

6020

6021

6022

6023

6024

6025

6026

6027

6028

6029

6030

# 

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

# 

 

from pyspark import since, keyword_only, SparkContext 

from pyspark.ml.linalg import _convert_to_vector 

from pyspark.ml.param.shared import HasThreshold, HasThresholds, HasInputCol, HasOutputCol, \ 

HasInputCols, HasOutputCols, HasHandleInvalid, HasRelativeError, HasFeaturesCol, HasLabelCol, \ 

HasSeed, HasNumFeatures, HasStepSize, HasMaxIter, TypeConverters, Param, Params 

from pyspark.ml.util import JavaMLReadable, JavaMLWritable 

from pyspark.ml.wrapper import JavaEstimator, JavaModel, JavaParams, JavaTransformer, _jvm 

from pyspark.ml.common import inherit_doc 

 

__all__ = ['Binarizer', 

'BucketedRandomProjectionLSH', 'BucketedRandomProjectionLSHModel', 

'Bucketizer', 

'ChiSqSelector', 'ChiSqSelectorModel', 

'CountVectorizer', 'CountVectorizerModel', 

'DCT', 

'ElementwiseProduct', 

'FeatureHasher', 

'HashingTF', 

'IDF', 'IDFModel', 

'Imputer', 'ImputerModel', 

'IndexToString', 

'Interaction', 

'MaxAbsScaler', 'MaxAbsScalerModel', 

'MinHashLSH', 'MinHashLSHModel', 

'MinMaxScaler', 'MinMaxScalerModel', 

'NGram', 

'Normalizer', 

'OneHotEncoder', 'OneHotEncoderModel', 

'PCA', 'PCAModel', 

'PolynomialExpansion', 

'QuantileDiscretizer', 

'RobustScaler', 'RobustScalerModel', 

'RegexTokenizer', 

'RFormula', 'RFormulaModel', 

'SQLTransformer', 

'StandardScaler', 'StandardScalerModel', 

'StopWordsRemover', 

'StringIndexer', 'StringIndexerModel', 

'Tokenizer', 

'UnivariateFeatureSelector', 'UnivariateFeatureSelectorModel', 

'VarianceThresholdSelector', 'VarianceThresholdSelectorModel', 

'VectorAssembler', 

'VectorIndexer', 'VectorIndexerModel', 

'VectorSizeHint', 

'VectorSlicer', 

'Word2Vec', 'Word2VecModel'] 

 

 

@inherit_doc 

class Binarizer(JavaTransformer, HasThreshold, HasThresholds, HasInputCol, HasOutputCol, 

HasInputCols, HasOutputCols, JavaMLReadable, JavaMLWritable): 

""" 

Binarize a column of continuous features given a threshold. Since 3.0.0, 

:py:class:`Binarize` can map multiple columns at once by setting the :py:attr:`inputCols` 

parameter. Note that when both the :py:attr:`inputCol` and :py:attr:`inputCols` parameters 

are set, an Exception will be thrown. The :py:attr:`threshold` parameter is used for 

single column usage, and :py:attr:`thresholds` is for multiple columns. 

 

.. versionadded:: 1.4.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(0.5,)], ["values"]) 

>>> binarizer = Binarizer(threshold=1.0, inputCol="values", outputCol="features") 

>>> binarizer.setThreshold(1.0) 

Binarizer... 

>>> binarizer.setInputCol("values") 

Binarizer... 

>>> binarizer.setOutputCol("features") 

Binarizer... 

>>> binarizer.transform(df).head().features 

0.0 

>>> binarizer.setParams(outputCol="freqs").transform(df).head().freqs 

0.0 

>>> params = {binarizer.threshold: -0.5, binarizer.outputCol: "vector"} 

>>> binarizer.transform(df, params).head().vector 

1.0 

>>> binarizerPath = temp_path + "/binarizer" 

>>> binarizer.save(binarizerPath) 

>>> loadedBinarizer = Binarizer.load(binarizerPath) 

>>> loadedBinarizer.getThreshold() == binarizer.getThreshold() 

True 

>>> loadedBinarizer.transform(df).take(1) == binarizer.transform(df).take(1) 

True 

>>> df2 = spark.createDataFrame([(0.5, 0.3)], ["values1", "values2"]) 

>>> binarizer2 = Binarizer(thresholds=[0.0, 1.0]) 

>>> binarizer2.setInputCols(["values1", "values2"]).setOutputCols(["output1", "output2"]) 

Binarizer... 

>>> binarizer2.transform(df2).show() 

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

|values1|values2|output1|output2| 

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

| 0.5| 0.3| 1.0| 0.0| 

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

... 

""" 

 

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

"Param for threshold used to binarize continuous features. " + 

"The features greater than the threshold will be binarized to 1.0. " + 

"The features equal to or less than the threshold will be binarized to 0.0", 

typeConverter=TypeConverters.toFloat) 

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

"Param for array of threshold used to binarize continuous features. " + 

"This is for multiple columns input. If transforming multiple columns " + 

"and thresholds is not set, but threshold is set, then threshold will " + 

"be applied across all columns.", 

typeConverter=TypeConverters.toListFloat) 

 

@keyword_only 

def __init__(self, *, threshold=0.0, inputCol=None, outputCol=None, thresholds=None, 

inputCols=None, outputCols=None): 

""" 

__init__(self, \\*, threshold=0.0, inputCol=None, outputCol=None, thresholds=None, \ 

inputCols=None, outputCols=None) 

""" 

super(Binarizer, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.Binarizer", self.uid) 

self._setDefault(threshold=0.0) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.4.0") 

def setParams(self, *, threshold=0.0, inputCol=None, outputCol=None, thresholds=None, 

inputCols=None, outputCols=None): 

""" 

setParams(self, \\*, threshold=0.0, inputCol=None, outputCol=None, thresholds=None, \ 

inputCols=None, outputCols=None) 

Sets params for this Binarizer. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("1.4.0") 

def setThreshold(self, value): 

""" 

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

""" 

return self._set(threshold=value) 

 

@since("3.0.0") 

def setThresholds(self, value): 

""" 

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

""" 

return self._set(thresholds=value) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

@since("3.0.0") 

def setInputCols(self, value): 

""" 

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

""" 

return self._set(inputCols=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

@since("3.0.0") 

def setOutputCols(self, value): 

""" 

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

""" 

return self._set(outputCols=value) 

 

 

class _LSHParams(HasInputCol, HasOutputCol): 

""" 

Mixin for Locality Sensitive Hashing (LSH) algorithm parameters. 

""" 

 

numHashTables = Param(Params._dummy(), "numHashTables", "number of hash tables, where " + 

"increasing number of hash tables lowers the false negative rate, " + 

"and decreasing it improves the running performance.", 

typeConverter=TypeConverters.toInt) 

 

def __init__(self, *args): 

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

self._setDefault(numHashTables=1) 

 

def getNumHashTables(self): 

""" 

Gets the value of numHashTables or its default value. 

""" 

return self.getOrDefault(self.numHashTables) 

 

 

class _LSH(JavaEstimator, _LSHParams, JavaMLReadable, JavaMLWritable): 

""" 

Mixin for Locality Sensitive Hashing (LSH). 

""" 

 

def setNumHashTables(self, value): 

""" 

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

""" 

return self._set(numHashTables=value) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

 

class _LSHModel(JavaModel, _LSHParams): 

""" 

Mixin for Locality Sensitive Hashing (LSH) models. 

""" 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

def approxNearestNeighbors(self, dataset, key, numNearestNeighbors, distCol="distCol"): 

""" 

Given a large dataset and an item, approximately find at most k items which have the 

closest distance to the item. If the :py:attr:`outputCol` is missing, the method will 

transform the data; if the :py:attr:`outputCol` exists, it will use that. This allows 

caching of the transformed data when necessary. 

 

Notes 

----- 

This method is experimental and will likely change behavior in the next release. 

 

Parameters 

---------- 

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

The dataset to search for nearest neighbors of the key. 

key : :py:class:`pyspark.ml.linalg.Vector` 

Feature vector representing the item to search for. 

numNearestNeighbors : int 

The maximum number of nearest neighbors. 

distCol : str 

Output column for storing the distance between each result row and the key. 

Use "distCol" as default value if it's not specified. 

 

Returns 

------- 

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

A dataset containing at most k items closest to the key. A column "distCol" is 

added to show the distance between each row and the key. 

""" 

return self._call_java("approxNearestNeighbors", dataset, key, numNearestNeighbors, 

distCol) 

 

def approxSimilarityJoin(self, datasetA, datasetB, threshold, distCol="distCol"): 

""" 

Join two datasets to approximately find all pairs of rows whose distance are smaller than 

the threshold. If the :py:attr:`outputCol` is missing, the method will transform the data; 

if the :py:attr:`outputCol` exists, it will use that. This allows caching of the 

transformed data when necessary. 

 

Parameters 

---------- 

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

One of the datasets to join. 

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

Another dataset to join. 

threshold : float 

The threshold for the distance of row pairs. 

distCol : str, optional 

Output column for storing the distance between each pair of rows. Use 

"distCol" as default value if it's not specified. 

 

Returns 

------- 

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

A joined dataset containing pairs of rows. The original rows are in columns 

"datasetA" and "datasetB", and a column "distCol" is added to show the distance 

between each pair. 

""" 

threshold = TypeConverters.toFloat(threshold) 

return self._call_java("approxSimilarityJoin", datasetA, datasetB, threshold, distCol) 

 

 

class _BucketedRandomProjectionLSHParams(): 

""" 

Params for :py:class:`BucketedRandomProjectionLSH` and 

:py:class:`BucketedRandomProjectionLSHModel`. 

 

.. versionadded:: 3.0.0 

""" 

 

bucketLength = Param(Params._dummy(), "bucketLength", "the length of each hash bucket, " + 

"a larger bucket lowers the false negative rate.", 

typeConverter=TypeConverters.toFloat) 

 

@since("2.2.0") 

def getBucketLength(self): 

""" 

Gets the value of bucketLength or its default value. 

""" 

return self.getOrDefault(self.bucketLength) 

 

 

@inherit_doc 

class BucketedRandomProjectionLSH(_LSH, _BucketedRandomProjectionLSHParams, 

HasSeed, JavaMLReadable, JavaMLWritable): 

""" 

LSH class for Euclidean distance metrics. 

The input is dense or sparse vectors, each of which represents a point in the Euclidean 

distance space. The output will be vectors of configurable dimension. Hash values in the same 

dimension are calculated by the same hash function. 

 

.. versionadded:: 2.2.0 

 

Notes 

----- 

 

- `Stable Distributions in Wikipedia article on Locality-sensitive hashing \ 

<https://en.wikipedia.org/wiki/Locality-sensitive_hashing#Stable_distributions>`_ 

- `Hashing for Similarity Search: A Survey <https://arxiv.org/abs/1408.2927>`_ 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

>>> from pyspark.sql.functions import col 

>>> data = [(0, Vectors.dense([-1.0, -1.0 ]),), 

... (1, Vectors.dense([-1.0, 1.0 ]),), 

... (2, Vectors.dense([1.0, -1.0 ]),), 

... (3, Vectors.dense([1.0, 1.0]),)] 

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

>>> brp = BucketedRandomProjectionLSH() 

>>> brp.setInputCol("features") 

BucketedRandomProjectionLSH... 

>>> brp.setOutputCol("hashes") 

BucketedRandomProjectionLSH... 

>>> brp.setSeed(12345) 

BucketedRandomProjectionLSH... 

>>> brp.setBucketLength(1.0) 

BucketedRandomProjectionLSH... 

>>> model = brp.fit(df) 

>>> model.getBucketLength() 

1.0 

>>> model.setOutputCol("hashes") 

BucketedRandomProjectionLSHModel... 

>>> model.transform(df).head() 

Row(id=0, features=DenseVector([-1.0, -1.0]), hashes=[DenseVector([-1.0])]) 

>>> data2 = [(4, Vectors.dense([2.0, 2.0 ]),), 

... (5, Vectors.dense([2.0, 3.0 ]),), 

... (6, Vectors.dense([3.0, 2.0 ]),), 

... (7, Vectors.dense([3.0, 3.0]),)] 

>>> df2 = spark.createDataFrame(data2, ["id", "features"]) 

>>> model.approxNearestNeighbors(df2, Vectors.dense([1.0, 2.0]), 1).collect() 

[Row(id=4, features=DenseVector([2.0, 2.0]), hashes=[DenseVector([1.0])], distCol=1.0)] 

>>> model.approxSimilarityJoin(df, df2, 3.0, distCol="EuclideanDistance").select( 

... col("datasetA.id").alias("idA"), 

... col("datasetB.id").alias("idB"), 

... col("EuclideanDistance")).show() 

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

|idA|idB|EuclideanDistance| 

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

| 3| 6| 2.23606797749979| 

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

... 

>>> model.approxSimilarityJoin(df, df2, 3, distCol="EuclideanDistance").select( 

... col("datasetA.id").alias("idA"), 

... col("datasetB.id").alias("idB"), 

... col("EuclideanDistance")).show() 

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

|idA|idB|EuclideanDistance| 

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

| 3| 6| 2.23606797749979| 

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

... 

>>> brpPath = temp_path + "/brp" 

>>> brp.save(brpPath) 

>>> brp2 = BucketedRandomProjectionLSH.load(brpPath) 

>>> brp2.getBucketLength() == brp.getBucketLength() 

True 

>>> modelPath = temp_path + "/brp-model" 

>>> model.save(modelPath) 

>>> model2 = BucketedRandomProjectionLSHModel.load(modelPath) 

>>> model.transform(df).head().hashes == model2.transform(df).head().hashes 

True 

""" 

 

@keyword_only 

def __init__(self, *, inputCol=None, outputCol=None, seed=None, numHashTables=1, 

bucketLength=None): 

""" 

__init__(self, \\*, inputCol=None, outputCol=None, seed=None, numHashTables=1, \ 

bucketLength=None) 

""" 

super(BucketedRandomProjectionLSH, self).__init__() 

self._java_obj = \ 

self._new_java_obj("org.apache.spark.ml.feature.BucketedRandomProjectionLSH", self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("2.2.0") 

def setParams(self, *, inputCol=None, outputCol=None, seed=None, numHashTables=1, 

bucketLength=None): 

""" 

setParams(self, \\*, inputCol=None, outputCol=None, seed=None, numHashTables=1, \ 

bucketLength=None) 

Sets params for this BucketedRandomProjectionLSH. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("2.2.0") 

def setBucketLength(self, value): 

""" 

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

""" 

return self._set(bucketLength=value) 

 

def setSeed(self, value): 

""" 

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

""" 

return self._set(seed=value) 

 

def _create_model(self, java_model): 

return BucketedRandomProjectionLSHModel(java_model) 

 

 

class BucketedRandomProjectionLSHModel(_LSHModel, _BucketedRandomProjectionLSHParams, 

JavaMLReadable, JavaMLWritable): 

r""" 

Model fitted by :py:class:`BucketedRandomProjectionLSH`, where multiple random vectors are 

stored. The vectors are normalized to be unit vectors and each vector is used in a hash 

function: :math:`h_i(x) = floor(r_i \cdot x / bucketLength)` where :math:`r_i` is the 

i-th random unit vector. The number of buckets will be `(max L2 norm of input vectors) / 

bucketLength`. 

 

.. versionadded:: 2.2.0 

""" 

 

 

@inherit_doc 

class Bucketizer(JavaTransformer, HasInputCol, HasOutputCol, HasInputCols, HasOutputCols, 

HasHandleInvalid, JavaMLReadable, JavaMLWritable): 

""" 

Maps a column of continuous features to a column of feature buckets. Since 3.0.0, 

:py:class:`Bucketizer` can map multiple columns at once by setting the :py:attr:`inputCols` 

parameter. Note that when both the :py:attr:`inputCol` and :py:attr:`inputCols` parameters 

are set, an Exception will be thrown. The :py:attr:`splits` parameter is only used for single 

column usage, and :py:attr:`splitsArray` is for multiple columns. 

 

.. versionadded:: 1.4.0 

 

Examples 

-------- 

>>> values = [(0.1, 0.0), (0.4, 1.0), (1.2, 1.3), (1.5, float("nan")), 

... (float("nan"), 1.0), (float("nan"), 0.0)] 

>>> df = spark.createDataFrame(values, ["values1", "values2"]) 

>>> bucketizer = Bucketizer() 

>>> bucketizer.setSplits([-float("inf"), 0.5, 1.4, float("inf")]) 

Bucketizer... 

>>> bucketizer.setInputCol("values1") 

Bucketizer... 

>>> bucketizer.setOutputCol("buckets") 

Bucketizer... 

>>> bucketed = bucketizer.setHandleInvalid("keep").transform(df).collect() 

>>> bucketed = bucketizer.setHandleInvalid("keep").transform(df.select("values1")) 

>>> bucketed.show(truncate=False) 

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

|values1|buckets| 

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

|0.1 |0.0 | 

|0.4 |0.0 | 

|1.2 |1.0 | 

|1.5 |2.0 | 

|NaN |3.0 | 

|NaN |3.0 | 

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

... 

>>> bucketizer.setParams(outputCol="b").transform(df).head().b 

0.0 

>>> bucketizerPath = temp_path + "/bucketizer" 

>>> bucketizer.save(bucketizerPath) 

>>> loadedBucketizer = Bucketizer.load(bucketizerPath) 

>>> loadedBucketizer.getSplits() == bucketizer.getSplits() 

True 

>>> loadedBucketizer.transform(df).take(1) == bucketizer.transform(df).take(1) 

True 

>>> bucketed = bucketizer.setHandleInvalid("skip").transform(df).collect() 

>>> len(bucketed) 

4 

>>> bucketizer2 = Bucketizer(splitsArray= 

... [[-float("inf"), 0.5, 1.4, float("inf")], [-float("inf"), 0.5, float("inf")]], 

... inputCols=["values1", "values2"], outputCols=["buckets1", "buckets2"]) 

>>> bucketed2 = bucketizer2.setHandleInvalid("keep").transform(df) 

>>> bucketed2.show(truncate=False) 

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

|values1|values2|buckets1|buckets2| 

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

|0.1 |0.0 |0.0 |0.0 | 

|0.4 |1.0 |0.0 |1.0 | 

|1.2 |1.3 |1.0 |1.0 | 

|1.5 |NaN |2.0 |2.0 | 

|NaN |1.0 |3.0 |1.0 | 

|NaN |0.0 |3.0 |0.0 | 

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

... 

""" 

 

splits = \ 

Param(Params._dummy(), "splits", 

"Split points for mapping continuous features into buckets. With n+1 splits, " + 

"there are n buckets. A bucket defined by splits x,y holds values in the " + 

"range [x,y) except the last bucket, which also includes y. The splits " + 

"should be of length >= 3 and strictly increasing. Values at -inf, inf must be " + 

"explicitly provided to cover all Double values; otherwise, values outside the " + 

"splits specified will be treated as errors.", 

typeConverter=TypeConverters.toListFloat) 

 

handleInvalid = Param(Params._dummy(), "handleInvalid", "how to handle invalid entries " 

"containing NaN values. Values outside the splits will always be treated " 

"as errors. Options are 'skip' (filter out rows with invalid values), " + 

"'error' (throw an error), or 'keep' (keep invalid values in a " + 

"special additional bucket). Note that in the multiple column " + 

"case, the invalid handling is applied to all columns. That said " + 

"for 'error' it will throw an error if any invalids are found in " + 

"any column, for 'skip' it will skip rows with any invalids in " + 

"any columns, etc.", 

typeConverter=TypeConverters.toString) 

 

splitsArray = Param(Params._dummy(), "splitsArray", "The array of split points for mapping " + 

"continuous features into buckets for multiple columns. For each input " + 

"column, with n+1 splits, there are n buckets. A bucket defined by " + 

"splits x,y holds values in the range [x,y) except the last bucket, " + 

"which also includes y. The splits should be of length >= 3 and " + 

"strictly increasing. Values at -inf, inf must be explicitly provided " + 

"to cover all Double values; otherwise, values outside the splits " + 

"specified will be treated as errors.", 

typeConverter=TypeConverters.toListListFloat) 

 

@keyword_only 

def __init__(self, *, splits=None, inputCol=None, outputCol=None, handleInvalid="error", 

splitsArray=None, inputCols=None, outputCols=None): 

""" 

__init__(self, \\*, splits=None, inputCol=None, outputCol=None, handleInvalid="error", \ 

splitsArray=None, inputCols=None, outputCols=None) 

""" 

super(Bucketizer, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.Bucketizer", self.uid) 

self._setDefault(handleInvalid="error") 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.4.0") 

def setParams(self, *, splits=None, inputCol=None, outputCol=None, handleInvalid="error", 

splitsArray=None, inputCols=None, outputCols=None): 

""" 

setParams(self, \\*, splits=None, inputCol=None, outputCol=None, handleInvalid="error", \ 

splitsArray=None, inputCols=None, outputCols=None) 

Sets params for this Bucketizer. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("1.4.0") 

def setSplits(self, value): 

""" 

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

""" 

return self._set(splits=value) 

 

@since("1.4.0") 

def getSplits(self): 

""" 

Gets the value of threshold or its default value. 

""" 

return self.getOrDefault(self.splits) 

 

@since("3.0.0") 

def setSplitsArray(self, value): 

""" 

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

""" 

return self._set(splitsArray=value) 

 

@since("3.0.0") 

def getSplitsArray(self): 

""" 

Gets the array of split points or its default value. 

""" 

return self.getOrDefault(self.splitsArray) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

@since("3.0.0") 

def setInputCols(self, value): 

""" 

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

""" 

return self._set(inputCols=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

@since("3.0.0") 

def setOutputCols(self, value): 

""" 

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

""" 

return self._set(outputCols=value) 

 

def setHandleInvalid(self, value): 

""" 

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

""" 

return self._set(handleInvalid=value) 

 

 

class _CountVectorizerParams(JavaParams, HasInputCol, HasOutputCol): 

""" 

Params for :py:class:`CountVectorizer` and :py:class:`CountVectorizerModel`. 

""" 

 

minTF = Param( 

Params._dummy(), "minTF", "Filter to ignore rare words in" + 

" a document. For each document, terms with frequency/count less than the given" + 

" threshold are ignored. If this is an integer >= 1, then this specifies a count (of" + 

" times the term must appear in the document); if this is a double in [0,1), then this " + 

"specifies a fraction (out of the document's token count). Note that the parameter is " + 

"only used in transform of CountVectorizerModel and does not affect fitting. Default 1.0", 

typeConverter=TypeConverters.toFloat) 

minDF = Param( 

Params._dummy(), "minDF", "Specifies the minimum number of" + 

" different documents a term must appear in to be included in the vocabulary." + 

" If this is an integer >= 1, this specifies the number of documents the term must" + 

" appear in; if this is a double in [0,1), then this specifies the fraction of documents." + 

" Default 1.0", typeConverter=TypeConverters.toFloat) 

maxDF = Param( 

Params._dummy(), "maxDF", "Specifies the maximum number of" + 

" different documents a term could appear in to be included in the vocabulary." + 

" A term that appears more than the threshold will be ignored. If this is an" + 

" integer >= 1, this specifies the maximum number of documents the term could appear in;" + 

" if this is a double in [0,1), then this specifies the maximum" + 

" fraction of documents the term could appear in." + 

" Default (2^63) - 1", typeConverter=TypeConverters.toFloat) 

vocabSize = Param( 

Params._dummy(), "vocabSize", "max size of the vocabulary. Default 1 << 18.", 

typeConverter=TypeConverters.toInt) 

binary = Param( 

Params._dummy(), "binary", "Binary toggle to control the output vector values." + 

" If True, all nonzero counts (after minTF filter applied) are set to 1. This is useful" + 

" for discrete probabilistic models that model binary events rather than integer counts." + 

" Default False", typeConverter=TypeConverters.toBoolean) 

 

def __init__(self, *args): 

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

self._setDefault(minTF=1.0, minDF=1.0, maxDF=2 ** 63 - 1, vocabSize=1 << 18, binary=False) 

 

@since("1.6.0") 

def getMinTF(self): 

""" 

Gets the value of minTF or its default value. 

""" 

return self.getOrDefault(self.minTF) 

 

@since("1.6.0") 

def getMinDF(self): 

""" 

Gets the value of minDF or its default value. 

""" 

return self.getOrDefault(self.minDF) 

 

@since("2.4.0") 

def getMaxDF(self): 

""" 

Gets the value of maxDF or its default value. 

""" 

return self.getOrDefault(self.maxDF) 

 

@since("1.6.0") 

def getVocabSize(self): 

""" 

Gets the value of vocabSize or its default value. 

""" 

return self.getOrDefault(self.vocabSize) 

 

@since("2.0.0") 

def getBinary(self): 

""" 

Gets the value of binary or its default value. 

""" 

return self.getOrDefault(self.binary) 

 

 

@inherit_doc 

class CountVectorizer(JavaEstimator, _CountVectorizerParams, JavaMLReadable, JavaMLWritable): 

""" 

Extracts a vocabulary from document collections and generates a :py:attr:`CountVectorizerModel`. 

 

.. versionadded:: 1.6.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame( 

... [(0, ["a", "b", "c"]), (1, ["a", "b", "b", "c", "a"])], 

... ["label", "raw"]) 

>>> cv = CountVectorizer() 

>>> cv.setInputCol("raw") 

CountVectorizer... 

>>> cv.setOutputCol("vectors") 

CountVectorizer... 

>>> model = cv.fit(df) 

>>> model.setInputCol("raw") 

CountVectorizerModel... 

>>> model.transform(df).show(truncate=False) 

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

|label|raw |vectors | 

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

|0 |[a, b, c] |(3,[0,1,2],[1.0,1.0,1.0])| 

|1 |[a, b, b, c, a]|(3,[0,1,2],[2.0,2.0,1.0])| 

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

... 

>>> sorted(model.vocabulary) == ['a', 'b', 'c'] 

True 

>>> countVectorizerPath = temp_path + "/count-vectorizer" 

>>> cv.save(countVectorizerPath) 

>>> loadedCv = CountVectorizer.load(countVectorizerPath) 

>>> loadedCv.getMinDF() == cv.getMinDF() 

True 

>>> loadedCv.getMinTF() == cv.getMinTF() 

True 

>>> loadedCv.getVocabSize() == cv.getVocabSize() 

True 

>>> modelPath = temp_path + "/count-vectorizer-model" 

>>> model.save(modelPath) 

>>> loadedModel = CountVectorizerModel.load(modelPath) 

>>> loadedModel.vocabulary == model.vocabulary 

True 

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

True 

>>> fromVocabModel = CountVectorizerModel.from_vocabulary(["a", "b", "c"], 

... inputCol="raw", outputCol="vectors") 

>>> fromVocabModel.transform(df).show(truncate=False) 

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

|label|raw |vectors | 

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

|0 |[a, b, c] |(3,[0,1,2],[1.0,1.0,1.0])| 

|1 |[a, b, b, c, a]|(3,[0,1,2],[2.0,2.0,1.0])| 

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

... 

""" 

 

@keyword_only 

def __init__(self, *, minTF=1.0, minDF=1.0, maxDF=2 ** 63 - 1, vocabSize=1 << 18, 

binary=False, inputCol=None, outputCol=None): 

""" 

__init__(self, \\*, minTF=1.0, minDF=1.0, maxDF=2 ** 63 - 1, vocabSize=1 << 18,\ 

binary=False, inputCol=None,outputCol=None) 

""" 

super(CountVectorizer, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.CountVectorizer", 

self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.6.0") 

def setParams(self, *, minTF=1.0, minDF=1.0, maxDF=2 ** 63 - 1, vocabSize=1 << 18, 

binary=False, inputCol=None, outputCol=None): 

""" 

setParams(self, \\*, minTF=1.0, minDF=1.0, maxDF=2 ** 63 - 1, vocabSize=1 << 18,\ 

binary=False, inputCol=None, outputCol=None) 

Set the params for the CountVectorizer 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("1.6.0") 

def setMinTF(self, value): 

""" 

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

""" 

return self._set(minTF=value) 

 

@since("1.6.0") 

def setMinDF(self, value): 

""" 

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

""" 

return self._set(minDF=value) 

 

@since("2.4.0") 

def setMaxDF(self, value): 

""" 

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

""" 

return self._set(maxDF=value) 

 

@since("1.6.0") 

def setVocabSize(self, value): 

""" 

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

""" 

return self._set(vocabSize=value) 

 

@since("2.0.0") 

def setBinary(self, value): 

""" 

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

""" 

return self._set(binary=value) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

def _create_model(self, java_model): 

return CountVectorizerModel(java_model) 

 

 

@inherit_doc 

class CountVectorizerModel(JavaModel, _CountVectorizerParams, JavaMLReadable, JavaMLWritable): 

""" 

Model fitted by :py:class:`CountVectorizer`. 

 

.. versionadded:: 1.6.0 

""" 

 

@since("3.0.0") 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

@since("3.0.0") 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

@classmethod 

@since("2.4.0") 

def from_vocabulary(cls, vocabulary, inputCol, outputCol=None, minTF=None, binary=None): 

""" 

Construct the model directly from a vocabulary list of strings, 

requires an active SparkContext. 

""" 

sc = SparkContext._active_spark_context 

java_class = sc._gateway.jvm.java.lang.String 

jvocab = CountVectorizerModel._new_java_array(vocabulary, java_class) 

model = CountVectorizerModel._create_from_java_class( 

"org.apache.spark.ml.feature.CountVectorizerModel", jvocab) 

model.setInputCol(inputCol) 

if outputCol is not None: 

model.setOutputCol(outputCol) 

if minTF is not None: 

model.setMinTF(minTF) 

908 ↛ 909line 908 didn't jump to line 909, because the condition on line 908 was never true if binary is not None: 

model.setBinary(binary) 

model._set(vocabSize=len(vocabulary)) 

return model 

 

@property 

@since("1.6.0") 

def vocabulary(self): 

""" 

An array of terms in the vocabulary. 

""" 

return self._call_java("vocabulary") 

 

@since("2.4.0") 

def setMinTF(self, value): 

""" 

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

""" 

return self._set(minTF=value) 

 

@since("2.4.0") 

def setBinary(self, value): 

""" 

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

""" 

return self._set(binary=value) 

 

 

@inherit_doc 

class DCT(JavaTransformer, HasInputCol, HasOutputCol, JavaMLReadable, JavaMLWritable): 

""" 

A feature transformer that takes the 1D discrete cosine transform 

of a real vector. No zero padding is performed on the input vector. 

It returns a real vector of the same length representing the DCT. 

The return vector is scaled such that the transform matrix is 

unitary (aka scaled DCT-II). 

 

.. versionadded:: 1.6.0 

 

Notes 

----- 

`More information on Wikipedia \ 

<https://en.wikipedia.org/wiki/Discrete_cosine_transform#DCT-II Wikipedia>`_. 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

>>> df1 = spark.createDataFrame([(Vectors.dense([5.0, 8.0, 6.0]),)], ["vec"]) 

>>> dct = DCT( ) 

>>> dct.setInverse(False) 

DCT... 

>>> dct.setInputCol("vec") 

DCT... 

>>> dct.setOutputCol("resultVec") 

DCT... 

>>> df2 = dct.transform(df1) 

>>> df2.head().resultVec 

DenseVector([10.969..., -0.707..., -2.041...]) 

>>> df3 = DCT(inverse=True, inputCol="resultVec", outputCol="origVec").transform(df2) 

>>> df3.head().origVec 

DenseVector([5.0, 8.0, 6.0]) 

>>> dctPath = temp_path + "/dct" 

>>> dct.save(dctPath) 

>>> loadedDtc = DCT.load(dctPath) 

>>> loadedDtc.transform(df1).take(1) == dct.transform(df1).take(1) 

True 

>>> loadedDtc.getInverse() 

False 

""" 

 

inverse = Param(Params._dummy(), "inverse", "Set transformer to perform inverse DCT, " + 

"default False.", typeConverter=TypeConverters.toBoolean) 

 

@keyword_only 

def __init__(self, *, inverse=False, inputCol=None, outputCol=None): 

""" 

__init__(self, \\*, inverse=False, inputCol=None, outputCol=None) 

""" 

super(DCT, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.DCT", self.uid) 

self._setDefault(inverse=False) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.6.0") 

def setParams(self, *, inverse=False, inputCol=None, outputCol=None): 

""" 

setParams(self, \\*, inverse=False, inputCol=None, outputCol=None) 

Sets params for this DCT. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("1.6.0") 

def setInverse(self, value): 

""" 

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

""" 

return self._set(inverse=value) 

 

@since("1.6.0") 

def getInverse(self): 

""" 

Gets the value of inverse or its default value. 

""" 

return self.getOrDefault(self.inverse) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

 

@inherit_doc 

class ElementwiseProduct(JavaTransformer, HasInputCol, HasOutputCol, JavaMLReadable, 

JavaMLWritable): 

""" 

Outputs the Hadamard product (i.e., the element-wise product) of each input vector 

with a provided "weight" vector. In other words, it scales each column of the dataset 

by a scalar multiplier. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

>>> df = spark.createDataFrame([(Vectors.dense([2.0, 1.0, 3.0]),)], ["values"]) 

>>> ep = ElementwiseProduct() 

>>> ep.setScalingVec(Vectors.dense([1.0, 2.0, 3.0])) 

ElementwiseProduct... 

>>> ep.setInputCol("values") 

ElementwiseProduct... 

>>> ep.setOutputCol("eprod") 

ElementwiseProduct... 

>>> ep.transform(df).head().eprod 

DenseVector([2.0, 2.0, 9.0]) 

>>> ep.setParams(scalingVec=Vectors.dense([2.0, 3.0, 5.0])).transform(df).head().eprod 

DenseVector([4.0, 3.0, 15.0]) 

>>> elementwiseProductPath = temp_path + "/elementwise-product" 

>>> ep.save(elementwiseProductPath) 

>>> loadedEp = ElementwiseProduct.load(elementwiseProductPath) 

>>> loadedEp.getScalingVec() == ep.getScalingVec() 

True 

>>> loadedEp.transform(df).take(1) == ep.transform(df).take(1) 

True 

""" 

 

scalingVec = Param(Params._dummy(), "scalingVec", "Vector for hadamard product.", 

typeConverter=TypeConverters.toVector) 

 

@keyword_only 

def __init__(self, *, scalingVec=None, inputCol=None, outputCol=None): 

""" 

__init__(self, \\*, scalingVec=None, inputCol=None, outputCol=None) 

""" 

super(ElementwiseProduct, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.ElementwiseProduct", 

self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.5.0") 

def setParams(self, *, scalingVec=None, inputCol=None, outputCol=None): 

""" 

setParams(self, \\*, scalingVec=None, inputCol=None, outputCol=None) 

Sets params for this ElementwiseProduct. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("2.0.0") 

def setScalingVec(self, value): 

""" 

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

""" 

return self._set(scalingVec=value) 

 

@since("2.0.0") 

def getScalingVec(self): 

""" 

Gets the value of scalingVec or its default value. 

""" 

return self.getOrDefault(self.scalingVec) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

 

@inherit_doc 

class FeatureHasher(JavaTransformer, HasInputCols, HasOutputCol, HasNumFeatures, JavaMLReadable, 

JavaMLWritable): 

""" 

Feature hashing projects a set of categorical or numerical features into a feature vector of 

specified dimension (typically substantially smaller than that of the original feature 

space). This is done using the hashing trick (https://en.wikipedia.org/wiki/Feature_hashing) 

to map features to indices in the feature vector. 

 

The FeatureHasher transformer operates on multiple columns. Each column may contain either 

numeric or categorical features. Behavior and handling of column data types is as follows: 

 

* Numeric columns: 

For numeric features, the hash value of the column name is used to map the 

feature value to its index in the feature vector. By default, numeric features 

are not treated as categorical (even when they are integers). To treat them 

as categorical, specify the relevant columns in `categoricalCols`. 

 

* String columns: 

For categorical features, the hash value of the string "column_name=value" 

is used to map to the vector index, with an indicator value of `1.0`. 

Thus, categorical features are "one-hot" encoded 

(similarly to using :py:class:`OneHotEncoder` with `dropLast=false`). 

 

* Boolean columns: 

Boolean values are treated in the same way as string columns. That is, 

boolean features are represented as "column_name=true" or "column_name=false", 

with an indicator value of `1.0`. 

 

Null (missing) values are ignored (implicitly zero in the resulting feature vector). 

 

Since a simple modulo is used to transform the hash function to a vector index, 

it is advisable to use a power of two as the `numFeatures` parameter; 

otherwise the features will not be mapped evenly to the vector indices. 

 

.. versionadded:: 2.3.0 

 

Examples 

-------- 

>>> data = [(2.0, True, "1", "foo"), (3.0, False, "2", "bar")] 

>>> cols = ["real", "bool", "stringNum", "string"] 

>>> df = spark.createDataFrame(data, cols) 

>>> hasher = FeatureHasher() 

>>> hasher.setInputCols(cols) 

FeatureHasher... 

>>> hasher.setOutputCol("features") 

FeatureHasher... 

>>> hasher.transform(df).head().features 

SparseVector(262144, {174475: 2.0, 247670: 1.0, 257907: 1.0, 262126: 1.0}) 

>>> hasher.setCategoricalCols(["real"]).transform(df).head().features 

SparseVector(262144, {171257: 1.0, 247670: 1.0, 257907: 1.0, 262126: 1.0}) 

>>> hasherPath = temp_path + "/hasher" 

>>> hasher.save(hasherPath) 

>>> loadedHasher = FeatureHasher.load(hasherPath) 

>>> loadedHasher.getNumFeatures() == hasher.getNumFeatures() 

True 

>>> loadedHasher.transform(df).head().features == hasher.transform(df).head().features 

True 

""" 

 

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

"numeric columns to treat as categorical", 

typeConverter=TypeConverters.toListString) 

 

@keyword_only 

def __init__(self, *, numFeatures=1 << 18, inputCols=None, outputCol=None, 

categoricalCols=None): 

""" 

__init__(self, \\*, numFeatures=1 << 18, inputCols=None, outputCol=None, \ 

categoricalCols=None) 

""" 

super(FeatureHasher, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.FeatureHasher", self.uid) 

self._setDefault(numFeatures=1 << 18) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("2.3.0") 

def setParams(self, *, numFeatures=1 << 18, inputCols=None, outputCol=None, 

categoricalCols=None): 

""" 

setParams(self, \\*, numFeatures=1 << 18, inputCols=None, outputCol=None, \ 

categoricalCols=None) 

Sets params for this FeatureHasher. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("2.3.0") 

def setCategoricalCols(self, value): 

""" 

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

""" 

return self._set(categoricalCols=value) 

 

@since("2.3.0") 

def getCategoricalCols(self): 

""" 

Gets the value of binary or its default value. 

""" 

return self.getOrDefault(self.categoricalCols) 

 

def setInputCols(self, value): 

""" 

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

""" 

return self._set(inputCols=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

def setNumFeatures(self, value): 

""" 

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

""" 

return self._set(numFeatures=value) 

 

 

@inherit_doc 

class HashingTF(JavaTransformer, HasInputCol, HasOutputCol, HasNumFeatures, JavaMLReadable, 

JavaMLWritable): 

""" 

Maps a sequence of terms to their term frequencies using the hashing trick. 

Currently we use Austin Appleby's MurmurHash 3 algorithm (MurmurHash3_x86_32) 

to calculate the hash code value for the term object. 

Since a simple modulo is used to transform the hash function to a column index, 

it is advisable to use a power of two as the numFeatures parameter; 

otherwise the features will not be mapped evenly to the columns. 

 

.. versionadded:: 1.3.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(["a", "b", "c"],)], ["words"]) 

>>> hashingTF = HashingTF(inputCol="words", outputCol="features") 

>>> hashingTF.setNumFeatures(10) 

HashingTF... 

>>> hashingTF.transform(df).head().features 

SparseVector(10, {5: 1.0, 7: 1.0, 8: 1.0}) 

>>> hashingTF.setParams(outputCol="freqs").transform(df).head().freqs 

SparseVector(10, {5: 1.0, 7: 1.0, 8: 1.0}) 

>>> params = {hashingTF.numFeatures: 5, hashingTF.outputCol: "vector"} 

>>> hashingTF.transform(df, params).head().vector 

SparseVector(5, {0: 1.0, 2: 1.0, 3: 1.0}) 

>>> hashingTFPath = temp_path + "/hashing-tf" 

>>> hashingTF.save(hashingTFPath) 

>>> loadedHashingTF = HashingTF.load(hashingTFPath) 

>>> loadedHashingTF.getNumFeatures() == hashingTF.getNumFeatures() 

True 

>>> loadedHashingTF.transform(df).take(1) == hashingTF.transform(df).take(1) 

True 

>>> hashingTF.indexOf("b") 

5 

""" 

 

binary = Param(Params._dummy(), "binary", "If True, all non zero counts are set to 1. " + 

"This is useful for discrete probabilistic models that model binary events " + 

"rather than integer counts. Default False.", 

typeConverter=TypeConverters.toBoolean) 

 

@keyword_only 

def __init__(self, *, numFeatures=1 << 18, binary=False, inputCol=None, outputCol=None): 

""" 

__init__(self, \\*, numFeatures=1 << 18, binary=False, inputCol=None, outputCol=None) 

""" 

super(HashingTF, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.HashingTF", self.uid) 

self._setDefault(numFeatures=1 << 18, binary=False) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.3.0") 

def setParams(self, *, numFeatures=1 << 18, binary=False, inputCol=None, outputCol=None): 

""" 

setParams(self, \\*, numFeatures=1 << 18, binary=False, inputCol=None, outputCol=None) 

Sets params for this HashingTF. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("2.0.0") 

def setBinary(self, value): 

""" 

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

""" 

return self._set(binary=value) 

 

@since("2.0.0") 

def getBinary(self): 

""" 

Gets the value of binary or its default value. 

""" 

return self.getOrDefault(self.binary) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

def setNumFeatures(self, value): 

""" 

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

""" 

return self._set(numFeatures=value) 

 

@since("3.0.0") 

def indexOf(self, term): 

""" 

Returns the index of the input term. 

""" 

self._transfer_params_to_java() 

return self._java_obj.indexOf(term) 

 

 

class _IDFParams(HasInputCol, HasOutputCol): 

""" 

Params for :py:class:`IDF` and :py:class:`IDFModel`. 

 

.. versionadded:: 3.0.0 

""" 

 

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

"minimum number of documents in which a term should appear for filtering", 

typeConverter=TypeConverters.toInt) 

 

@since("1.4.0") 

def getMinDocFreq(self): 

""" 

Gets the value of minDocFreq or its default value. 

""" 

return self.getOrDefault(self.minDocFreq) 

 

def __init__(self, *args): 

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

self._setDefault(minDocFreq=0) 

 

 

@inherit_doc 

class IDF(JavaEstimator, _IDFParams, JavaMLReadable, JavaMLWritable): 

""" 

Compute the Inverse Document Frequency (IDF) given a collection of documents. 

 

.. versionadded:: 1.4.0 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import DenseVector 

>>> df = spark.createDataFrame([(DenseVector([1.0, 2.0]),), 

... (DenseVector([0.0, 1.0]),), (DenseVector([3.0, 0.2]),)], ["tf"]) 

>>> idf = IDF(minDocFreq=3) 

>>> idf.setInputCol("tf") 

IDF... 

>>> idf.setOutputCol("idf") 

IDF... 

>>> model = idf.fit(df) 

>>> model.setOutputCol("idf") 

IDFModel... 

>>> model.getMinDocFreq() 

3 

>>> model.idf 

DenseVector([0.0, 0.0]) 

>>> model.docFreq 

[0, 3] 

>>> model.numDocs == df.count() 

True 

>>> model.transform(df).head().idf 

DenseVector([0.0, 0.0]) 

>>> idf.setParams(outputCol="freqs").fit(df).transform(df).collect()[1].freqs 

DenseVector([0.0, 0.0]) 

>>> params = {idf.minDocFreq: 1, idf.outputCol: "vector"} 

>>> idf.fit(df, params).transform(df).head().vector 

DenseVector([0.2877, 0.0]) 

>>> idfPath = temp_path + "/idf" 

>>> idf.save(idfPath) 

>>> loadedIdf = IDF.load(idfPath) 

>>> loadedIdf.getMinDocFreq() == idf.getMinDocFreq() 

True 

>>> modelPath = temp_path + "/idf-model" 

>>> model.save(modelPath) 

>>> loadedModel = IDFModel.load(modelPath) 

>>> loadedModel.transform(df).head().idf == model.transform(df).head().idf 

True 

""" 

 

@keyword_only 

def __init__(self, *, minDocFreq=0, inputCol=None, outputCol=None): 

""" 

__init__(self, \\*, minDocFreq=0, inputCol=None, outputCol=None) 

""" 

super(IDF, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.IDF", self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.4.0") 

def setParams(self, *, minDocFreq=0, inputCol=None, outputCol=None): 

""" 

setParams(self, \\*, minDocFreq=0, inputCol=None, outputCol=None) 

Sets params for this IDF. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("1.4.0") 

def setMinDocFreq(self, value): 

""" 

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

""" 

return self._set(minDocFreq=value) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

def _create_model(self, java_model): 

return IDFModel(java_model) 

 

 

class IDFModel(JavaModel, _IDFParams, JavaMLReadable, JavaMLWritable): 

""" 

Model fitted by :py:class:`IDF`. 

 

.. versionadded:: 1.4.0 

""" 

 

@since("3.0.0") 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

@since("3.0.0") 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

@property 

@since("2.0.0") 

def idf(self): 

""" 

Returns the IDF vector. 

""" 

return self._call_java("idf") 

 

@property 

@since("3.0.0") 

def docFreq(self): 

""" 

Returns the document frequency. 

""" 

return self._call_java("docFreq") 

 

@property 

@since("3.0.0") 

def numDocs(self): 

""" 

Returns number of documents evaluated to compute idf 

""" 

return self._call_java("numDocs") 

 

 

class _ImputerParams(HasInputCol, HasInputCols, HasOutputCol, HasOutputCols, HasRelativeError): 

""" 

Params for :py:class:`Imputer` and :py:class:`ImputerModel`. 

 

.. versionadded:: 3.0.0 

""" 

 

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

"strategy for imputation. If mean, then replace missing values using the mean " 

"value of the feature. If median, then replace missing values using the " 

"median value of the feature. If mode, then replace missing using the most " 

"frequent value of the feature.", 

typeConverter=TypeConverters.toString) 

 

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

"The placeholder for the missing values. All occurrences of missingValue " 

"will be imputed.", typeConverter=TypeConverters.toFloat) 

 

def __init__(self, *args): 

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

self._setDefault(strategy="mean", missingValue=float("nan"), relativeError=0.001) 

 

@since("2.2.0") 

def getStrategy(self): 

""" 

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

""" 

return self.getOrDefault(self.strategy) 

 

@since("2.2.0") 

def getMissingValue(self): 

""" 

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

""" 

return self.getOrDefault(self.missingValue) 

 

 

@inherit_doc 

class Imputer(JavaEstimator, _ImputerParams, JavaMLReadable, JavaMLWritable): 

""" 

Imputation estimator for completing missing values, using the mean, median or mode 

of the columns in which the missing values are located. The input columns should be of 

numeric type. Currently Imputer does not support categorical features and 

possibly creates incorrect values for a categorical feature. 

 

Note that the mean/median/mode value is computed after filtering out missing values. 

All Null values in the input columns are treated as missing, and so are also imputed. For 

computing median, :py:meth:`pyspark.sql.DataFrame.approxQuantile` is used with a 

relative error of `0.001`. 

 

.. versionadded:: 2.2.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(1.0, float("nan")), (2.0, float("nan")), (float("nan"), 3.0), 

... (4.0, 4.0), (5.0, 5.0)], ["a", "b"]) 

>>> imputer = Imputer() 

>>> imputer.setInputCols(["a", "b"]) 

Imputer... 

>>> imputer.setOutputCols(["out_a", "out_b"]) 

Imputer... 

>>> imputer.getRelativeError() 

0.001 

>>> model = imputer.fit(df) 

>>> model.setInputCols(["a", "b"]) 

ImputerModel... 

>>> model.getStrategy() 

'mean' 

>>> model.surrogateDF.show() 

+---+---+ 

| a| b| 

+---+---+ 

|3.0|4.0| 

+---+---+ 

... 

>>> model.transform(df).show() 

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

| a| b|out_a|out_b| 

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

|1.0|NaN| 1.0| 4.0| 

|2.0|NaN| 2.0| 4.0| 

|NaN|3.0| 3.0| 3.0| 

... 

>>> imputer.setStrategy("median").setMissingValue(1.0).fit(df).transform(df).show() 

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

| a| b|out_a|out_b| 

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

|1.0|NaN| 4.0| NaN| 

... 

>>> df1 = spark.createDataFrame([(1.0,), (2.0,), (float("nan"),), (4.0,), (5.0,)], ["a"]) 

>>> imputer1 = Imputer(inputCol="a", outputCol="out_a") 

>>> model1 = imputer1.fit(df1) 

>>> model1.surrogateDF.show() 

+---+ 

| a| 

+---+ 

|3.0| 

+---+ 

... 

>>> model1.transform(df1).show() 

+---+-----+ 

| a|out_a| 

+---+-----+ 

|1.0| 1.0| 

|2.0| 2.0| 

|NaN| 3.0| 

... 

>>> imputer1.setStrategy("median").setMissingValue(1.0).fit(df1).transform(df1).show() 

+---+-----+ 

| a|out_a| 

+---+-----+ 

|1.0| 4.0| 

... 

>>> df2 = spark.createDataFrame([(float("nan"),), (float("nan"),), (3.0,), (4.0,), (5.0,)], 

... ["b"]) 

>>> imputer2 = Imputer(inputCol="b", outputCol="out_b") 

>>> model2 = imputer2.fit(df2) 

>>> model2.surrogateDF.show() 

+---+ 

| b| 

+---+ 

|4.0| 

+---+ 

... 

>>> model2.transform(df2).show() 

+---+-----+ 

| b|out_b| 

+---+-----+ 

|NaN| 4.0| 

|NaN| 4.0| 

|3.0| 3.0| 

... 

>>> imputer2.setStrategy("median").setMissingValue(1.0).fit(df2).transform(df2).show() 

+---+-----+ 

| b|out_b| 

+---+-----+ 

|NaN| NaN| 

... 

>>> imputerPath = temp_path + "/imputer" 

>>> imputer.save(imputerPath) 

>>> loadedImputer = Imputer.load(imputerPath) 

>>> loadedImputer.getStrategy() == imputer.getStrategy() 

True 

>>> loadedImputer.getMissingValue() 

1.0 

>>> modelPath = temp_path + "/imputer-model" 

>>> model.save(modelPath) 

>>> loadedModel = ImputerModel.load(modelPath) 

>>> loadedModel.transform(df).head().out_a == model.transform(df).head().out_a 

True 

""" 

 

@keyword_only 

def __init__(self, *, strategy="mean", missingValue=float("nan"), inputCols=None, 

outputCols=None, inputCol=None, outputCol=None, relativeError=0.001): 

""" 

__init__(self, \\*, strategy="mean", missingValue=float("nan"), inputCols=None, \ 

outputCols=None, inputCol=None, outputCol=None, relativeError=0.001): 

""" 

super(Imputer, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.Imputer", self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("2.2.0") 

def setParams(self, *, strategy="mean", missingValue=float("nan"), inputCols=None, 

outputCols=None, inputCol=None, outputCol=None, relativeError=0.001): 

""" 

setParams(self, \\*, strategy="mean", missingValue=float("nan"), inputCols=None, \ 

outputCols=None, inputCol=None, outputCol=None, relativeError=0.001) 

Sets params for this Imputer. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("2.2.0") 

def setStrategy(self, value): 

""" 

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

""" 

return self._set(strategy=value) 

 

@since("2.2.0") 

def setMissingValue(self, value): 

""" 

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

""" 

return self._set(missingValue=value) 

 

@since("2.2.0") 

def setInputCols(self, value): 

""" 

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

""" 

return self._set(inputCols=value) 

 

@since("2.2.0") 

def setOutputCols(self, value): 

""" 

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

""" 

return self._set(outputCols=value) 

 

@since("3.0.0") 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

@since("3.0.0") 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

@since("3.0.0") 

def setRelativeError(self, value): 

""" 

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

""" 

return self._set(relativeError=value) 

 

def _create_model(self, java_model): 

return ImputerModel(java_model) 

 

 

class ImputerModel(JavaModel, _ImputerParams, JavaMLReadable, JavaMLWritable): 

""" 

Model fitted by :py:class:`Imputer`. 

 

.. versionadded:: 2.2.0 

""" 

 

@since("3.0.0") 

def setInputCols(self, value): 

""" 

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

""" 

return self._set(inputCols=value) 

 

@since("3.0.0") 

def setOutputCols(self, value): 

""" 

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

""" 

return self._set(outputCols=value) 

 

@since("3.0.0") 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

@since("3.0.0") 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

@property 

@since("2.2.0") 

def surrogateDF(self): 

""" 

Returns a DataFrame containing inputCols and their corresponding surrogates, 

which are used to replace the missing values in the input DataFrame. 

""" 

return self._call_java("surrogateDF") 

 

 

@inherit_doc 

class Interaction(JavaTransformer, HasInputCols, HasOutputCol, JavaMLReadable, JavaMLWritable): 

""" 

Implements the feature interaction transform. This transformer takes in Double and Vector type 

columns and outputs a flattened vector of their feature interactions. To handle interaction, 

we first one-hot encode any nominal features. Then, a vector of the feature cross-products is 

produced. 

 

For example, given the input feature values `Double(2)` and `Vector(3, 4)`, the output would be 

`Vector(6, 8)` if all input features were numeric. If the first feature was instead nominal 

with four categories, the output would then be `Vector(0, 0, 0, 0, 3, 4, 0, 0)`. 

 

.. versionadded:: 3.0.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(0.0, 1.0), (2.0, 3.0)], ["a", "b"]) 

>>> interaction = Interaction() 

>>> interaction.setInputCols(["a", "b"]) 

Interaction... 

>>> interaction.setOutputCol("ab") 

Interaction... 

>>> interaction.transform(df).show() 

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

| a| b| ab| 

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

|0.0|1.0|[0.0]| 

|2.0|3.0|[6.0]| 

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

... 

>>> interactionPath = temp_path + "/interaction" 

>>> interaction.save(interactionPath) 

>>> loadedInteraction = Interaction.load(interactionPath) 

>>> loadedInteraction.transform(df).head().ab == interaction.transform(df).head().ab 

True 

""" 

 

@keyword_only 

def __init__(self, *, inputCols=None, outputCol=None): 

""" 

__init__(self, \\*, inputCols=None, outputCol=None): 

""" 

super(Interaction, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.Interaction", self.uid) 

self._setDefault() 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("3.0.0") 

def setParams(self, *, inputCols=None, outputCol=None): 

""" 

setParams(self, \\*, inputCols=None, outputCol=None) 

Sets params for this Interaction. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("3.0.0") 

def setInputCols(self, value): 

""" 

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

""" 

return self._set(inputCols=value) 

 

@since("3.0.0") 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

 

class _MaxAbsScalerParams(HasInputCol, HasOutputCol): 

""" 

Params for :py:class:`MaxAbsScaler` and :py:class:`MaxAbsScalerModel`. 

 

.. versionadded:: 3.0.0 

""" 

pass 

 

 

@inherit_doc 

class MaxAbsScaler(JavaEstimator, _MaxAbsScalerParams, JavaMLReadable, JavaMLWritable): 

""" 

Rescale each feature individually to range [-1, 1] by dividing through the largest maximum 

absolute value in each feature. It does not shift/center the data, and thus does not destroy 

any sparsity. 

 

.. versionadded:: 2.0.0 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

>>> df = spark.createDataFrame([(Vectors.dense([1.0]),), (Vectors.dense([2.0]),)], ["a"]) 

>>> maScaler = MaxAbsScaler(outputCol="scaled") 

>>> maScaler.setInputCol("a") 

MaxAbsScaler... 

>>> model = maScaler.fit(df) 

>>> model.setOutputCol("scaledOutput") 

MaxAbsScalerModel... 

>>> model.transform(df).show() 

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

| a|scaledOutput| 

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

|[1.0]| [0.5]| 

|[2.0]| [1.0]| 

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

... 

>>> scalerPath = temp_path + "/max-abs-scaler" 

>>> maScaler.save(scalerPath) 

>>> loadedMAScaler = MaxAbsScaler.load(scalerPath) 

>>> loadedMAScaler.getInputCol() == maScaler.getInputCol() 

True 

>>> loadedMAScaler.getOutputCol() == maScaler.getOutputCol() 

True 

>>> modelPath = temp_path + "/max-abs-scaler-model" 

>>> model.save(modelPath) 

>>> loadedModel = MaxAbsScalerModel.load(modelPath) 

>>> loadedModel.maxAbs == model.maxAbs 

True 

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

True 

""" 

 

@keyword_only 

def __init__(self, *, inputCol=None, outputCol=None): 

""" 

__init__(self, \\*, inputCol=None, outputCol=None) 

""" 

super(MaxAbsScaler, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.MaxAbsScaler", self.uid) 

self._setDefault() 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("2.0.0") 

def setParams(self, *, inputCol=None, outputCol=None): 

""" 

setParams(self, \\*, inputCol=None, outputCol=None) 

Sets params for this MaxAbsScaler. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

def _create_model(self, java_model): 

return MaxAbsScalerModel(java_model) 

 

 

class MaxAbsScalerModel(JavaModel, _MaxAbsScalerParams, JavaMLReadable, JavaMLWritable): 

""" 

Model fitted by :py:class:`MaxAbsScaler`. 

 

.. versionadded:: 2.0.0 

""" 

 

@since("3.0.0") 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

@since("3.0.0") 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

@property 

@since("2.0.0") 

def maxAbs(self): 

""" 

Max Abs vector. 

""" 

return self._call_java("maxAbs") 

 

 

@inherit_doc 

class MinHashLSH(_LSH, HasInputCol, HasOutputCol, HasSeed, JavaMLReadable, JavaMLWritable): 

 

""" 

LSH class for Jaccard distance. 

The input can be dense or sparse vectors, but it is more efficient if it is sparse. 

For example, `Vectors.sparse(10, [(2, 1.0), (3, 1.0), (5, 1.0)])` means there are 10 elements 

in the space. This set contains elements 2, 3, and 5. Also, any input vector must have at 

least 1 non-zero index, and all non-zero values are treated as binary "1" values. 

 

.. versionadded:: 2.2.0 

 

Notes 

----- 

See `Wikipedia on MinHash <https://en.wikipedia.org/wiki/MinHash>`_ 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

>>> from pyspark.sql.functions import col 

>>> data = [(0, Vectors.sparse(6, [0, 1, 2], [1.0, 1.0, 1.0]),), 

... (1, Vectors.sparse(6, [2, 3, 4], [1.0, 1.0, 1.0]),), 

... (2, Vectors.sparse(6, [0, 2, 4], [1.0, 1.0, 1.0]),)] 

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

>>> mh = MinHashLSH() 

>>> mh.setInputCol("features") 

MinHashLSH... 

>>> mh.setOutputCol("hashes") 

MinHashLSH... 

>>> mh.setSeed(12345) 

MinHashLSH... 

>>> model = mh.fit(df) 

>>> model.setInputCol("features") 

MinHashLSHModel... 

>>> model.transform(df).head() 

Row(id=0, features=SparseVector(6, {0: 1.0, 1: 1.0, 2: 1.0}), hashes=[DenseVector([6179668... 

>>> data2 = [(3, Vectors.sparse(6, [1, 3, 5], [1.0, 1.0, 1.0]),), 

... (4, Vectors.sparse(6, [2, 3, 5], [1.0, 1.0, 1.0]),), 

... (5, Vectors.sparse(6, [1, 2, 4], [1.0, 1.0, 1.0]),)] 

>>> df2 = spark.createDataFrame(data2, ["id", "features"]) 

>>> key = Vectors.sparse(6, [1, 2], [1.0, 1.0]) 

>>> model.approxNearestNeighbors(df2, key, 1).collect() 

[Row(id=5, features=SparseVector(6, {1: 1.0, 2: 1.0, 4: 1.0}), hashes=[DenseVector([6179668... 

>>> model.approxSimilarityJoin(df, df2, 0.6, distCol="JaccardDistance").select( 

... col("datasetA.id").alias("idA"), 

... col("datasetB.id").alias("idB"), 

... col("JaccardDistance")).show() 

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

|idA|idB|JaccardDistance| 

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

| 0| 5| 0.5| 

| 1| 4| 0.5| 

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

... 

>>> mhPath = temp_path + "/mh" 

>>> mh.save(mhPath) 

>>> mh2 = MinHashLSH.load(mhPath) 

>>> mh2.getOutputCol() == mh.getOutputCol() 

True 

>>> modelPath = temp_path + "/mh-model" 

>>> model.save(modelPath) 

>>> model2 = MinHashLSHModel.load(modelPath) 

>>> model.transform(df).head().hashes == model2.transform(df).head().hashes 

True 

""" 

 

@keyword_only 

def __init__(self, *, inputCol=None, outputCol=None, seed=None, numHashTables=1): 

""" 

__init__(self, \\*, inputCol=None, outputCol=None, seed=None, numHashTables=1) 

""" 

super(MinHashLSH, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.MinHashLSH", self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("2.2.0") 

def setParams(self, *, inputCol=None, outputCol=None, seed=None, numHashTables=1): 

""" 

setParams(self, \\*, inputCol=None, outputCol=None, seed=None, numHashTables=1) 

Sets params for this MinHashLSH. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

def setSeed(self, value): 

""" 

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

""" 

return self._set(seed=value) 

 

def _create_model(self, java_model): 

return MinHashLSHModel(java_model) 

 

 

class MinHashLSHModel(_LSHModel, JavaMLReadable, JavaMLWritable): 

r""" 

Model produced by :py:class:`MinHashLSH`, where where multiple hash functions are stored. Each 

hash function is picked from the following family of hash functions, where :math:`a_i` and 

:math:`b_i` are randomly chosen integers less than prime: 

:math:`h_i(x) = ((x \cdot a_i + b_i) \mod prime)` This hash family is approximately min-wise 

independent according to the reference. 

 

.. versionadded:: 2.2.0 

 

Notes 

----- 

See Tom Bohman, Colin Cooper, and Alan Frieze. "Min-wise independent linear permutations." 

Electronic Journal of Combinatorics 7 (2000): R26. 

""" 

 

 

class _MinMaxScalerParams(HasInputCol, HasOutputCol): 

""" 

Params for :py:class:`MinMaxScaler` and :py:class:`MinMaxScalerModel`. 

 

.. versionadded:: 3.0.0 

""" 

 

min = Param(Params._dummy(), "min", "Lower bound of the output feature range", 

typeConverter=TypeConverters.toFloat) 

max = Param(Params._dummy(), "max", "Upper bound of the output feature range", 

typeConverter=TypeConverters.toFloat) 

 

def __init__(self, *args): 

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

self._setDefault(min=0.0, max=1.0) 

 

@since("1.6.0") 

def getMin(self): 

""" 

Gets the value of min or its default value. 

""" 

return self.getOrDefault(self.min) 

 

@since("1.6.0") 

def getMax(self): 

""" 

Gets the value of max or its default value. 

""" 

return self.getOrDefault(self.max) 

 

 

@inherit_doc 

class MinMaxScaler(JavaEstimator, _MinMaxScalerParams, JavaMLReadable, JavaMLWritable): 

""" 

Rescale each feature individually to a common range [min, max] linearly using column summary 

statistics, which is also known as min-max normalization or Rescaling. The rescaled value for 

feature E is calculated as, 

 

Rescaled(e_i) = (e_i - E_min) / (E_max - E_min) * (max - min) + min 

 

For the case E_max == E_min, Rescaled(e_i) = 0.5 * (max + min) 

 

.. versionadded:: 1.6.0 

 

Notes 

----- 

Since zero values will probably be transformed to non-zero values, output of the 

transformer will be DenseVector even for sparse input. 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

>>> df = spark.createDataFrame([(Vectors.dense([0.0]),), (Vectors.dense([2.0]),)], ["a"]) 

>>> mmScaler = MinMaxScaler(outputCol="scaled") 

>>> mmScaler.setInputCol("a") 

MinMaxScaler... 

>>> model = mmScaler.fit(df) 

>>> model.setOutputCol("scaledOutput") 

MinMaxScalerModel... 

>>> model.originalMin 

DenseVector([0.0]) 

>>> model.originalMax 

DenseVector([2.0]) 

>>> model.transform(df).show() 

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

| a|scaledOutput| 

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

|[0.0]| [0.0]| 

|[2.0]| [1.0]| 

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

... 

>>> minMaxScalerPath = temp_path + "/min-max-scaler" 

>>> mmScaler.save(minMaxScalerPath) 

>>> loadedMMScaler = MinMaxScaler.load(minMaxScalerPath) 

>>> loadedMMScaler.getMin() == mmScaler.getMin() 

True 

>>> loadedMMScaler.getMax() == mmScaler.getMax() 

True 

>>> modelPath = temp_path + "/min-max-scaler-model" 

>>> model.save(modelPath) 

>>> loadedModel = MinMaxScalerModel.load(modelPath) 

>>> loadedModel.originalMin == model.originalMin 

True 

>>> loadedModel.originalMax == model.originalMax 

True 

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

True 

""" 

 

@keyword_only 

def __init__(self, *, min=0.0, max=1.0, inputCol=None, outputCol=None): 

""" 

__init__(self, \\*, min=0.0, max=1.0, inputCol=None, outputCol=None) 

""" 

super(MinMaxScaler, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.MinMaxScaler", self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.6.0") 

def setParams(self, *, min=0.0, max=1.0, inputCol=None, outputCol=None): 

""" 

setParams(self, \\*, min=0.0, max=1.0, inputCol=None, outputCol=None) 

Sets params for this MinMaxScaler. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("1.6.0") 

def setMin(self, value): 

""" 

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

""" 

return self._set(min=value) 

 

@since("1.6.0") 

def setMax(self, value): 

""" 

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

""" 

return self._set(max=value) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

def _create_model(self, java_model): 

return MinMaxScalerModel(java_model) 

 

 

class MinMaxScalerModel(JavaModel, _MinMaxScalerParams, JavaMLReadable, JavaMLWritable): 

""" 

Model fitted by :py:class:`MinMaxScaler`. 

 

.. versionadded:: 1.6.0 

""" 

 

@since("3.0.0") 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

@since("3.0.0") 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

@since("3.0.0") 

def setMin(self, value): 

""" 

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

""" 

return self._set(min=value) 

 

@since("3.0.0") 

def setMax(self, value): 

""" 

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

""" 

return self._set(max=value) 

 

@property 

@since("2.0.0") 

def originalMin(self): 

""" 

Min value for each original column during fitting. 

""" 

return self._call_java("originalMin") 

 

@property 

@since("2.0.0") 

def originalMax(self): 

""" 

Max value for each original column during fitting. 

""" 

return self._call_java("originalMax") 

 

 

@inherit_doc 

class NGram(JavaTransformer, HasInputCol, HasOutputCol, JavaMLReadable, JavaMLWritable): 

""" 

A feature transformer that converts the input array of strings into an array of n-grams. Null 

values in the input array are ignored. 

It returns an array of n-grams where each n-gram is represented by a space-separated string of 

words. 

When the input is empty, an empty array is returned. 

When the input array length is less than n (number of elements per n-gram), no n-grams are 

returned. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([Row(inputTokens=["a", "b", "c", "d", "e"])]) 

>>> ngram = NGram(n=2) 

>>> ngram.setInputCol("inputTokens") 

NGram... 

>>> ngram.setOutputCol("nGrams") 

NGram... 

>>> ngram.transform(df).head() 

Row(inputTokens=['a', 'b', 'c', 'd', 'e'], nGrams=['a b', 'b c', 'c d', 'd e']) 

>>> # Change n-gram length 

>>> ngram.setParams(n=4).transform(df).head() 

Row(inputTokens=['a', 'b', 'c', 'd', 'e'], nGrams=['a b c d', 'b c d e']) 

>>> # Temporarily modify output column. 

>>> ngram.transform(df, {ngram.outputCol: "output"}).head() 

Row(inputTokens=['a', 'b', 'c', 'd', 'e'], output=['a b c d', 'b c d e']) 

>>> ngram.transform(df).head() 

Row(inputTokens=['a', 'b', 'c', 'd', 'e'], nGrams=['a b c d', 'b c d e']) 

>>> # Must use keyword arguments to specify params. 

>>> ngram.setParams("text") 

Traceback (most recent call last): 

... 

TypeError: Method setParams forces keyword arguments. 

>>> ngramPath = temp_path + "/ngram" 

>>> ngram.save(ngramPath) 

>>> loadedNGram = NGram.load(ngramPath) 

>>> loadedNGram.getN() == ngram.getN() 

True 

>>> loadedNGram.transform(df).take(1) == ngram.transform(df).take(1) 

True 

""" 

 

n = Param(Params._dummy(), "n", "number of elements per n-gram (>=1)", 

typeConverter=TypeConverters.toInt) 

 

@keyword_only 

def __init__(self, *, n=2, inputCol=None, outputCol=None): 

""" 

__init__(self, \\*, n=2, inputCol=None, outputCol=None) 

""" 

super(NGram, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.NGram", self.uid) 

self._setDefault(n=2) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.5.0") 

def setParams(self, *, n=2, inputCol=None, outputCol=None): 

""" 

setParams(self, \\*, n=2, inputCol=None, outputCol=None) 

Sets params for this NGram. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("1.5.0") 

def setN(self, value): 

""" 

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

""" 

return self._set(n=value) 

 

@since("1.5.0") 

def getN(self): 

""" 

Gets the value of n or its default value. 

""" 

return self.getOrDefault(self.n) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

 

@inherit_doc 

class Normalizer(JavaTransformer, HasInputCol, HasOutputCol, JavaMLReadable, JavaMLWritable): 

""" 

Normalize a vector to have unit norm using the given p-norm. 

 

.. versionadded:: 1.4.0 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

>>> svec = Vectors.sparse(4, {1: 4.0, 3: 3.0}) 

>>> df = spark.createDataFrame([(Vectors.dense([3.0, -4.0]), svec)], ["dense", "sparse"]) 

>>> normalizer = Normalizer(p=2.0) 

>>> normalizer.setInputCol("dense") 

Normalizer... 

>>> normalizer.setOutputCol("features") 

Normalizer... 

>>> normalizer.transform(df).head().features 

DenseVector([0.6, -0.8]) 

>>> normalizer.setParams(inputCol="sparse", outputCol="freqs").transform(df).head().freqs 

SparseVector(4, {1: 0.8, 3: 0.6}) 

>>> params = {normalizer.p: 1.0, normalizer.inputCol: "dense", normalizer.outputCol: "vector"} 

>>> normalizer.transform(df, params).head().vector 

DenseVector([0.4286, -0.5714]) 

>>> normalizerPath = temp_path + "/normalizer" 

>>> normalizer.save(normalizerPath) 

>>> loadedNormalizer = Normalizer.load(normalizerPath) 

>>> loadedNormalizer.getP() == normalizer.getP() 

True 

>>> loadedNormalizer.transform(df).take(1) == normalizer.transform(df).take(1) 

True 

""" 

 

p = Param(Params._dummy(), "p", "the p norm value.", 

typeConverter=TypeConverters.toFloat) 

 

@keyword_only 

def __init__(self, *, p=2.0, inputCol=None, outputCol=None): 

""" 

__init__(self, \\*, p=2.0, inputCol=None, outputCol=None) 

""" 

super(Normalizer, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.Normalizer", self.uid) 

self._setDefault(p=2.0) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.4.0") 

def setParams(self, *, p=2.0, inputCol=None, outputCol=None): 

""" 

setParams(self, \\*, p=2.0, inputCol=None, outputCol=None) 

Sets params for this Normalizer. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("1.4.0") 

def setP(self, value): 

""" 

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

""" 

return self._set(p=value) 

 

@since("1.4.0") 

def getP(self): 

""" 

Gets the value of p or its default value. 

""" 

return self.getOrDefault(self.p) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

 

class _OneHotEncoderParams(HasInputCol, HasInputCols, HasOutputCol, HasOutputCols, 

HasHandleInvalid): 

""" 

Params for :py:class:`OneHotEncoder` and :py:class:`OneHotEncoderModel`. 

 

.. versionadded:: 3.0.0 

""" 

 

handleInvalid = Param(Params._dummy(), "handleInvalid", "How to handle invalid data during " + 

"transform(). Options are 'keep' (invalid data presented as an extra " + 

"categorical feature) or error (throw an error). Note that this Param " + 

"is only used during transform; during fitting, invalid data will " + 

"result in an error.", 

typeConverter=TypeConverters.toString) 

 

dropLast = Param(Params._dummy(), "dropLast", "whether to drop the last category", 

typeConverter=TypeConverters.toBoolean) 

 

def __init__(self, *args): 

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

self._setDefault(handleInvalid="error", dropLast=True) 

 

@since("2.3.0") 

def getDropLast(self): 

""" 

Gets the value of dropLast or its default value. 

""" 

return self.getOrDefault(self.dropLast) 

 

 

@inherit_doc 

class OneHotEncoder(JavaEstimator, _OneHotEncoderParams, JavaMLReadable, JavaMLWritable): 

""" 

A one-hot encoder that maps a column of category indices to a column of binary vectors, with 

at most a single one-value per row that indicates the input category index. 

For example with 5 categories, an input value of 2.0 would map to an output vector of 

`[0.0, 0.0, 1.0, 0.0]`. 

The last category is not included by default (configurable via :py:attr:`dropLast`), 

because it makes the vector entries sum up to one, and hence linearly dependent. 

So an input value of 4.0 maps to `[0.0, 0.0, 0.0, 0.0]`. 

 

When :py:attr:`handleInvalid` is configured to 'keep', an extra "category" indicating invalid 

values is added as last category. So when :py:attr:`dropLast` is true, invalid values are 

encoded as all-zeros vector. 

 

.. versionadded:: 2.3.0 

 

Notes 

----- 

This is different from scikit-learn's OneHotEncoder, which keeps all categories. 

The output vectors are sparse. 

 

When encoding multi-column by using :py:attr:`inputCols` and 

:py:attr:`outputCols` params, input/output cols come in pairs, specified by the order in 

the arrays, and each pair is treated independently. 

 

See Also 

-------- 

StringIndexer : for converting categorical values into category indices 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

>>> df = spark.createDataFrame([(0.0,), (1.0,), (2.0,)], ["input"]) 

>>> ohe = OneHotEncoder() 

>>> ohe.setInputCols(["input"]) 

OneHotEncoder... 

>>> ohe.setOutputCols(["output"]) 

OneHotEncoder... 

>>> model = ohe.fit(df) 

>>> model.setOutputCols(["output"]) 

OneHotEncoderModel... 

>>> model.getHandleInvalid() 

'error' 

>>> model.transform(df).head().output 

SparseVector(2, {0: 1.0}) 

>>> single_col_ohe = OneHotEncoder(inputCol="input", outputCol="output") 

>>> single_col_model = single_col_ohe.fit(df) 

>>> single_col_model.transform(df).head().output 

SparseVector(2, {0: 1.0}) 

>>> ohePath = temp_path + "/ohe" 

>>> ohe.save(ohePath) 

>>> loadedOHE = OneHotEncoder.load(ohePath) 

>>> loadedOHE.getInputCols() == ohe.getInputCols() 

True 

>>> modelPath = temp_path + "/ohe-model" 

>>> model.save(modelPath) 

>>> loadedModel = OneHotEncoderModel.load(modelPath) 

>>> loadedModel.categorySizes == model.categorySizes 

True 

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

True 

""" 

 

@keyword_only 

def __init__(self, *, inputCols=None, outputCols=None, handleInvalid="error", dropLast=True, 

inputCol=None, outputCol=None): 

""" 

__init__(self, \\*, inputCols=None, outputCols=None, handleInvalid="error", dropLast=True, \ 

inputCol=None, outputCol=None) 

""" 

super(OneHotEncoder, self).__init__() 

self._java_obj = self._new_java_obj( 

"org.apache.spark.ml.feature.OneHotEncoder", self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("2.3.0") 

def setParams(self, *, inputCols=None, outputCols=None, handleInvalid="error", 

dropLast=True, inputCol=None, outputCol=None): 

""" 

setParams(self, \\*, inputCols=None, outputCols=None, handleInvalid="error", \ 

dropLast=True, inputCol=None, outputCol=None) 

Sets params for this OneHotEncoder. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("2.3.0") 

def setDropLast(self, value): 

""" 

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

""" 

return self._set(dropLast=value) 

 

@since("3.0.0") 

def setInputCols(self, value): 

""" 

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

""" 

return self._set(inputCols=value) 

 

@since("3.0.0") 

def setOutputCols(self, value): 

""" 

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

""" 

return self._set(outputCols=value) 

 

@since("3.0.0") 

def setHandleInvalid(self, value): 

""" 

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

""" 

return self._set(handleInvalid=value) 

 

@since("3.0.0") 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

@since("3.0.0") 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

def _create_model(self, java_model): 

return OneHotEncoderModel(java_model) 

 

 

class OneHotEncoderModel(JavaModel, _OneHotEncoderParams, JavaMLReadable, JavaMLWritable): 

""" 

Model fitted by :py:class:`OneHotEncoder`. 

 

.. versionadded:: 2.3.0 

""" 

 

@since("3.0.0") 

def setDropLast(self, value): 

""" 

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

""" 

return self._set(dropLast=value) 

 

@since("3.0.0") 

def setInputCols(self, value): 

""" 

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

""" 

return self._set(inputCols=value) 

 

@since("3.0.0") 

def setOutputCols(self, value): 

""" 

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

""" 

return self._set(outputCols=value) 

 

@since("3.0.0") 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

@since("3.0.0") 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

@since("3.0.0") 

def setHandleInvalid(self, value): 

""" 

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

""" 

return self._set(handleInvalid=value) 

 

@property 

@since("2.3.0") 

def categorySizes(self): 

""" 

Original number of categories for each feature being encoded. 

The array contains one value for each input column, in order. 

""" 

return self._call_java("categorySizes") 

 

 

@inherit_doc 

class PolynomialExpansion(JavaTransformer, HasInputCol, HasOutputCol, JavaMLReadable, 

JavaMLWritable): 

""" 

Perform feature expansion in a polynomial space. As said in `wikipedia of Polynomial Expansion 

<http://en.wikipedia.org/wiki/Polynomial_expansion>`_, "In mathematics, an 

expansion of a product of sums expresses it as a sum of products by using the fact that 

multiplication distributes over addition". Take a 2-variable feature vector as an example: 

`(x, y)`, if we want to expand it with degree 2, then we get `(x, x * x, y, x * y, y * y)`. 

 

.. versionadded:: 1.4.0 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

>>> df = spark.createDataFrame([(Vectors.dense([0.5, 2.0]),)], ["dense"]) 

>>> px = PolynomialExpansion(degree=2) 

>>> px.setInputCol("dense") 

PolynomialExpansion... 

>>> px.setOutputCol("expanded") 

PolynomialExpansion... 

>>> px.transform(df).head().expanded 

DenseVector([0.5, 0.25, 2.0, 1.0, 4.0]) 

>>> px.setParams(outputCol="test").transform(df).head().test 

DenseVector([0.5, 0.25, 2.0, 1.0, 4.0]) 

>>> polyExpansionPath = temp_path + "/poly-expansion" 

>>> px.save(polyExpansionPath) 

>>> loadedPx = PolynomialExpansion.load(polyExpansionPath) 

>>> loadedPx.getDegree() == px.getDegree() 

True 

>>> loadedPx.transform(df).take(1) == px.transform(df).take(1) 

True 

""" 

 

degree = Param(Params._dummy(), "degree", "the polynomial degree to expand (>= 1)", 

typeConverter=TypeConverters.toInt) 

 

@keyword_only 

def __init__(self, *, degree=2, inputCol=None, outputCol=None): 

""" 

__init__(self, \\*, degree=2, inputCol=None, outputCol=None) 

""" 

super(PolynomialExpansion, self).__init__() 

self._java_obj = self._new_java_obj( 

"org.apache.spark.ml.feature.PolynomialExpansion", self.uid) 

self._setDefault(degree=2) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.4.0") 

def setParams(self, *, degree=2, inputCol=None, outputCol=None): 

""" 

setParams(self, \\*, degree=2, inputCol=None, outputCol=None) 

Sets params for this PolynomialExpansion. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("1.4.0") 

def setDegree(self, value): 

""" 

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

""" 

return self._set(degree=value) 

 

@since("1.4.0") 

def getDegree(self): 

""" 

Gets the value of degree or its default value. 

""" 

return self.getOrDefault(self.degree) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

 

@inherit_doc 

class QuantileDiscretizer(JavaEstimator, HasInputCol, HasOutputCol, HasInputCols, HasOutputCols, 

HasHandleInvalid, HasRelativeError, JavaMLReadable, JavaMLWritable): 

""" 

:py:class:`QuantileDiscretizer` takes a column with continuous features and outputs a column 

with binned categorical features. The number of bins can be set using the :py:attr:`numBuckets` 

parameter. It is possible that the number of buckets used will be less than this value, for 

example, if there are too few distinct values of the input to create enough distinct quantiles. 

Since 3.0.0, :py:class:`QuantileDiscretizer` can map multiple columns at once by setting the 

:py:attr:`inputCols` parameter. If both of the :py:attr:`inputCol` and :py:attr:`inputCols` 

parameters are set, an Exception will be thrown. To specify the number of buckets for each 

column, the :py:attr:`numBucketsArray` parameter can be set, or if the number of buckets 

should be the same across columns, :py:attr:`numBuckets` can be set as a convenience. 

 

.. versionadded:: 2.0.0 

 

Notes 

----- 

NaN handling: Note also that 

:py:class:`QuantileDiscretizer` will raise an error when it finds NaN values in the dataset, 

but the user can also choose to either keep or remove NaN values within the dataset by setting 

:py:attr:`handleInvalid` parameter. If the user chooses to keep NaN values, they will be 

handled specially and placed into their own bucket, for example, if 4 buckets are used, then 

non-NaN data will be put into buckets[0-3], but NaNs will be counted in a special bucket[4]. 

 

Algorithm: The bin ranges are chosen using an approximate algorithm (see the documentation for 

:py:meth:`~.DataFrameStatFunctions.approxQuantile` for a detailed description). 

The precision of the approximation can be controlled with the 

:py:attr:`relativeError` parameter. 

The lower and upper bin bounds will be `-Infinity` and `+Infinity`, covering all real values. 

 

Examples 

-------- 

>>> values = [(0.1,), (0.4,), (1.2,), (1.5,), (float("nan"),), (float("nan"),)] 

>>> df1 = spark.createDataFrame(values, ["values"]) 

>>> qds1 = QuantileDiscretizer(inputCol="values", outputCol="buckets") 

>>> qds1.setNumBuckets(2) 

QuantileDiscretizer... 

>>> qds1.setRelativeError(0.01) 

QuantileDiscretizer... 

>>> qds1.setHandleInvalid("error") 

QuantileDiscretizer... 

>>> qds1.getRelativeError() 

0.01 

>>> bucketizer = qds1.fit(df1) 

>>> qds1.setHandleInvalid("keep").fit(df1).transform(df1).count() 

6 

>>> qds1.setHandleInvalid("skip").fit(df1).transform(df1).count() 

4 

>>> splits = bucketizer.getSplits() 

>>> splits[0] 

-inf 

>>> print("%2.1f" % round(splits[1], 1)) 

0.4 

>>> bucketed = bucketizer.transform(df1).head() 

>>> bucketed.buckets 

0.0 

>>> quantileDiscretizerPath = temp_path + "/quantile-discretizer" 

>>> qds1.save(quantileDiscretizerPath) 

>>> loadedQds = QuantileDiscretizer.load(quantileDiscretizerPath) 

>>> loadedQds.getNumBuckets() == qds1.getNumBuckets() 

True 

>>> inputs = [(0.1, 0.0), (0.4, 1.0), (1.2, 1.3), (1.5, 1.5), 

... (float("nan"), float("nan")), (float("nan"), float("nan"))] 

>>> df2 = spark.createDataFrame(inputs, ["input1", "input2"]) 

>>> qds2 = QuantileDiscretizer(relativeError=0.01, handleInvalid="error", numBuckets=2, 

... inputCols=["input1", "input2"], outputCols=["output1", "output2"]) 

>>> qds2.getRelativeError() 

0.01 

>>> qds2.setHandleInvalid("keep").fit(df2).transform(df2).show() 

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

|input1|input2|output1|output2| 

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

| 0.1| 0.0| 0.0| 0.0| 

| 0.4| 1.0| 1.0| 1.0| 

| 1.2| 1.3| 1.0| 1.0| 

| 1.5| 1.5| 1.0| 1.0| 

| NaN| NaN| 2.0| 2.0| 

| NaN| NaN| 2.0| 2.0| 

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

... 

>>> qds3 = QuantileDiscretizer(relativeError=0.01, handleInvalid="error", 

... numBucketsArray=[5, 10], inputCols=["input1", "input2"], 

... outputCols=["output1", "output2"]) 

>>> qds3.setHandleInvalid("skip").fit(df2).transform(df2).show() 

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

|input1|input2|output1|output2| 

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

| 0.1| 0.0| 1.0| 1.0| 

| 0.4| 1.0| 2.0| 2.0| 

| 1.2| 1.3| 3.0| 3.0| 

| 1.5| 1.5| 4.0| 4.0| 

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

... 

""" 

 

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

"Maximum number of buckets (quantiles, or " + 

"categories) into which data points are grouped. Must be >= 2.", 

typeConverter=TypeConverters.toInt) 

 

handleInvalid = Param(Params._dummy(), "handleInvalid", "how to handle invalid entries. " + 

"Options are skip (filter out rows with invalid values), " + 

"error (throw an error), or keep (keep invalid values in a special " + 

"additional bucket). Note that in the multiple columns " + 

"case, the invalid handling is applied to all columns. That said " + 

"for 'error' it will throw an error if any invalids are found in " + 

"any columns, for 'skip' it will skip rows with any invalids in " + 

"any columns, etc.", 

typeConverter=TypeConverters.toString) 

 

numBucketsArray = Param(Params._dummy(), "numBucketsArray", "Array of number of buckets " + 

"(quantiles, or categories) into which data points are grouped. " + 

"This is for multiple columns input. If transforming multiple " + 

"columns and numBucketsArray is not set, but numBuckets is set, " + 

"then numBuckets will be applied across all columns.", 

typeConverter=TypeConverters.toListInt) 

 

@keyword_only 

def __init__(self, *, numBuckets=2, inputCol=None, outputCol=None, relativeError=0.001, 

handleInvalid="error", numBucketsArray=None, inputCols=None, outputCols=None): 

""" 

__init__(self, \\*, numBuckets=2, inputCol=None, outputCol=None, relativeError=0.001, \ 

handleInvalid="error", numBucketsArray=None, inputCols=None, outputCols=None) 

""" 

super(QuantileDiscretizer, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.QuantileDiscretizer", 

self.uid) 

self._setDefault(numBuckets=2, relativeError=0.001, handleInvalid="error") 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("2.0.0") 

def setParams(self, *, numBuckets=2, inputCol=None, outputCol=None, relativeError=0.001, 

handleInvalid="error", numBucketsArray=None, inputCols=None, outputCols=None): 

""" 

setParams(self, \\*, numBuckets=2, inputCol=None, outputCol=None, relativeError=0.001, \ 

handleInvalid="error", numBucketsArray=None, inputCols=None, outputCols=None) 

Set the params for the QuantileDiscretizer 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("2.0.0") 

def setNumBuckets(self, value): 

""" 

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

""" 

return self._set(numBuckets=value) 

 

@since("2.0.0") 

def getNumBuckets(self): 

""" 

Gets the value of numBuckets or its default value. 

""" 

return self.getOrDefault(self.numBuckets) 

 

@since("3.0.0") 

def setNumBucketsArray(self, value): 

""" 

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

""" 

return self._set(numBucketsArray=value) 

 

@since("3.0.0") 

def getNumBucketsArray(self): 

""" 

Gets the value of numBucketsArray or its default value. 

""" 

return self.getOrDefault(self.numBucketsArray) 

 

@since("2.0.0") 

def setRelativeError(self, value): 

""" 

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

""" 

return self._set(relativeError=value) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

@since("3.0.0") 

def setInputCols(self, value): 

""" 

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

""" 

return self._set(inputCols=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

@since("3.0.0") 

def setOutputCols(self, value): 

""" 

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

""" 

return self._set(outputCols=value) 

 

def setHandleInvalid(self, value): 

""" 

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

""" 

return self._set(handleInvalid=value) 

 

def _create_model(self, java_model): 

""" 

Private method to convert the java_model to a Python model. 

""" 

if (self.isSet(self.inputCol)): 

return Bucketizer(splits=list(java_model.getSplits()), 

inputCol=self.getInputCol(), 

outputCol=self.getOutputCol(), 

handleInvalid=self.getHandleInvalid()) 

else: 

splitsArrayList = [list(x) for x in list(java_model.getSplitsArray())] 

return Bucketizer(splitsArray=splitsArrayList, 

inputCols=self.getInputCols(), 

outputCols=self.getOutputCols(), 

handleInvalid=self.getHandleInvalid()) 

 

 

class _RobustScalerParams(HasInputCol, HasOutputCol, HasRelativeError): 

""" 

Params for :py:class:`RobustScaler` and :py:class:`RobustScalerModel`. 

 

.. versionadded:: 3.0.0 

""" 

 

lower = Param(Params._dummy(), "lower", "Lower quantile to calculate quantile range", 

typeConverter=TypeConverters.toFloat) 

upper = Param(Params._dummy(), "upper", "Upper quantile to calculate quantile range", 

typeConverter=TypeConverters.toFloat) 

withCentering = Param(Params._dummy(), "withCentering", "Whether to center data with median", 

typeConverter=TypeConverters.toBoolean) 

withScaling = Param(Params._dummy(), "withScaling", "Whether to scale the data to " 

"quantile range", typeConverter=TypeConverters.toBoolean) 

 

def __init__(self, *args): 

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

self._setDefault(lower=0.25, upper=0.75, withCentering=False, withScaling=True, 

relativeError=0.001) 

 

@since("3.0.0") 

def getLower(self): 

""" 

Gets the value of lower or its default value. 

""" 

return self.getOrDefault(self.lower) 

 

@since("3.0.0") 

def getUpper(self): 

""" 

Gets the value of upper or its default value. 

""" 

return self.getOrDefault(self.upper) 

 

@since("3.0.0") 

def getWithCentering(self): 

""" 

Gets the value of withCentering or its default value. 

""" 

return self.getOrDefault(self.withCentering) 

 

@since("3.0.0") 

def getWithScaling(self): 

""" 

Gets the value of withScaling or its default value. 

""" 

return self.getOrDefault(self.withScaling) 

 

 

@inherit_doc 

class RobustScaler(JavaEstimator, _RobustScalerParams, JavaMLReadable, JavaMLWritable): 

""" 

RobustScaler removes the median and scales the data according to the quantile range. 

The quantile range is by default IQR (Interquartile Range, quantile range between the 

1st quartile = 25th quantile and the 3rd quartile = 75th quantile) but can be configured. 

Centering and scaling happen independently on each feature by computing the relevant 

statistics on the samples in the training set. Median and quantile range are then 

stored to be used on later data using the transform method. 

Note that NaN values are ignored in the computation of medians and ranges. 

 

.. versionadded:: 3.0.0 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

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

... (1, Vectors.dense([1.0, -1.0]),), 

... (2, Vectors.dense([2.0, -2.0]),), 

... (3, Vectors.dense([3.0, -3.0]),), 

... (4, Vectors.dense([4.0, -4.0]),),] 

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

>>> scaler = RobustScaler() 

>>> scaler.setInputCol("features") 

RobustScaler... 

>>> scaler.setOutputCol("scaled") 

RobustScaler... 

>>> model = scaler.fit(df) 

>>> model.setOutputCol("output") 

RobustScalerModel... 

>>> model.median 

DenseVector([2.0, -2.0]) 

>>> model.range 

DenseVector([2.0, 2.0]) 

>>> model.transform(df).collect()[1].output 

DenseVector([0.5, -0.5]) 

>>> scalerPath = temp_path + "/robust-scaler" 

>>> scaler.save(scalerPath) 

>>> loadedScaler = RobustScaler.load(scalerPath) 

>>> loadedScaler.getWithCentering() == scaler.getWithCentering() 

True 

>>> loadedScaler.getWithScaling() == scaler.getWithScaling() 

True 

>>> modelPath = temp_path + "/robust-scaler-model" 

>>> model.save(modelPath) 

>>> loadedModel = RobustScalerModel.load(modelPath) 

>>> loadedModel.median == model.median 

True 

>>> loadedModel.range == model.range 

True 

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

True 

""" 

 

@keyword_only 

def __init__(self, *, lower=0.25, upper=0.75, withCentering=False, withScaling=True, 

inputCol=None, outputCol=None, relativeError=0.001): 

""" 

__init__(self, \\*, lower=0.25, upper=0.75, withCentering=False, withScaling=True, \ 

inputCol=None, outputCol=None, relativeError=0.001) 

""" 

super(RobustScaler, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.RobustScaler", self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("3.0.0") 

def setParams(self, *, lower=0.25, upper=0.75, withCentering=False, withScaling=True, 

inputCol=None, outputCol=None, relativeError=0.001): 

""" 

setParams(self, \\*, lower=0.25, upper=0.75, withCentering=False, withScaling=True, \ 

inputCol=None, outputCol=None, relativeError=0.001) 

Sets params for this RobustScaler. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("3.0.0") 

def setLower(self, value): 

""" 

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

""" 

return self._set(lower=value) 

 

@since("3.0.0") 

def setUpper(self, value): 

""" 

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

""" 

return self._set(upper=value) 

 

@since("3.0.0") 

def setWithCentering(self, value): 

""" 

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

""" 

return self._set(withCentering=value) 

 

@since("3.0.0") 

def setWithScaling(self, value): 

""" 

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

""" 

return self._set(withScaling=value) 

 

@since("3.0.0") 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

@since("3.0.0") 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

@since("3.0.0") 

def setRelativeError(self, value): 

""" 

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

""" 

return self._set(relativeError=value) 

 

def _create_model(self, java_model): 

return RobustScalerModel(java_model) 

 

 

class RobustScalerModel(JavaModel, _RobustScalerParams, JavaMLReadable, JavaMLWritable): 

""" 

Model fitted by :py:class:`RobustScaler`. 

 

.. versionadded:: 3.0.0 

""" 

 

@since("3.0.0") 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

@since("3.0.0") 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

@property 

@since("3.0.0") 

def median(self): 

""" 

Median of the RobustScalerModel. 

""" 

return self._call_java("median") 

 

@property 

@since("3.0.0") 

def range(self): 

""" 

Quantile range of the RobustScalerModel. 

""" 

return self._call_java("range") 

 

 

@inherit_doc 

class RegexTokenizer(JavaTransformer, HasInputCol, HasOutputCol, JavaMLReadable, JavaMLWritable): 

""" 

A regex based tokenizer that extracts tokens either by using the 

provided regex pattern (in Java dialect) to split the text 

(default) or repeatedly matching the regex (if gaps is false). 

Optional parameters also allow filtering tokens using a minimal 

length. 

It returns an array of strings that can be empty. 

 

.. versionadded:: 1.4.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([("A B c",)], ["text"]) 

>>> reTokenizer = RegexTokenizer() 

>>> reTokenizer.setInputCol("text") 

RegexTokenizer... 

>>> reTokenizer.setOutputCol("words") 

RegexTokenizer... 

>>> reTokenizer.transform(df).head() 

Row(text='A B c', words=['a', 'b', 'c']) 

>>> # Change a parameter. 

>>> reTokenizer.setParams(outputCol="tokens").transform(df).head() 

Row(text='A B c', tokens=['a', 'b', 'c']) 

>>> # Temporarily modify a parameter. 

>>> reTokenizer.transform(df, {reTokenizer.outputCol: "words"}).head() 

Row(text='A B c', words=['a', 'b', 'c']) 

>>> reTokenizer.transform(df).head() 

Row(text='A B c', tokens=['a', 'b', 'c']) 

>>> # Must use keyword arguments to specify params. 

>>> reTokenizer.setParams("text") 

Traceback (most recent call last): 

... 

TypeError: Method setParams forces keyword arguments. 

>>> regexTokenizerPath = temp_path + "/regex-tokenizer" 

>>> reTokenizer.save(regexTokenizerPath) 

>>> loadedReTokenizer = RegexTokenizer.load(regexTokenizerPath) 

>>> loadedReTokenizer.getMinTokenLength() == reTokenizer.getMinTokenLength() 

True 

>>> loadedReTokenizer.getGaps() == reTokenizer.getGaps() 

True 

>>> loadedReTokenizer.transform(df).take(1) == reTokenizer.transform(df).take(1) 

True 

""" 

 

minTokenLength = Param(Params._dummy(), "minTokenLength", "minimum token length (>= 0)", 

typeConverter=TypeConverters.toInt) 

gaps = Param(Params._dummy(), "gaps", "whether regex splits on gaps (True) or matches tokens " + 

"(False)") 

pattern = Param(Params._dummy(), "pattern", "regex pattern (Java dialect) used for tokenizing", 

typeConverter=TypeConverters.toString) 

toLowercase = Param(Params._dummy(), "toLowercase", "whether to convert all characters to " + 

"lowercase before tokenizing", typeConverter=TypeConverters.toBoolean) 

 

@keyword_only 

def __init__(self, *, minTokenLength=1, gaps=True, pattern="\\s+", inputCol=None, 

outputCol=None, toLowercase=True): 

""" 

__init__(self, \\*, minTokenLength=1, gaps=True, pattern="\\s+", inputCol=None, \ 

outputCol=None, toLowercase=True) 

""" 

super(RegexTokenizer, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.RegexTokenizer", self.uid) 

self._setDefault(minTokenLength=1, gaps=True, pattern="\\s+", toLowercase=True) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.4.0") 

def setParams(self, *, minTokenLength=1, gaps=True, pattern="\\s+", inputCol=None, 

outputCol=None, toLowercase=True): 

""" 

setParams(self, \\*, minTokenLength=1, gaps=True, pattern="\\s+", inputCol=None, \ 

outputCol=None, toLowercase=True) 

Sets params for this RegexTokenizer. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("1.4.0") 

def setMinTokenLength(self, value): 

""" 

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

""" 

return self._set(minTokenLength=value) 

 

@since("1.4.0") 

def getMinTokenLength(self): 

""" 

Gets the value of minTokenLength or its default value. 

""" 

return self.getOrDefault(self.minTokenLength) 

 

@since("1.4.0") 

def setGaps(self, value): 

""" 

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

""" 

return self._set(gaps=value) 

 

@since("1.4.0") 

def getGaps(self): 

""" 

Gets the value of gaps or its default value. 

""" 

return self.getOrDefault(self.gaps) 

 

@since("1.4.0") 

def setPattern(self, value): 

""" 

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

""" 

return self._set(pattern=value) 

 

@since("1.4.0") 

def getPattern(self): 

""" 

Gets the value of pattern or its default value. 

""" 

return self.getOrDefault(self.pattern) 

 

@since("2.0.0") 

def setToLowercase(self, value): 

""" 

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

""" 

return self._set(toLowercase=value) 

 

@since("2.0.0") 

def getToLowercase(self): 

""" 

Gets the value of toLowercase or its default value. 

""" 

return self.getOrDefault(self.toLowercase) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

 

@inherit_doc 

class SQLTransformer(JavaTransformer, JavaMLReadable, JavaMLWritable): 

""" 

Implements the transforms which are defined by SQL statement. 

Currently we only support SQL syntax like `SELECT ... FROM __THIS__` 

where `__THIS__` represents the underlying table of the input dataset. 

 

.. versionadded:: 1.6.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(0, 1.0, 3.0), (2, 2.0, 5.0)], ["id", "v1", "v2"]) 

>>> sqlTrans = SQLTransformer( 

... statement="SELECT *, (v1 + v2) AS v3, (v1 * v2) AS v4 FROM __THIS__") 

>>> sqlTrans.transform(df).head() 

Row(id=0, v1=1.0, v2=3.0, v3=4.0, v4=3.0) 

>>> sqlTransformerPath = temp_path + "/sql-transformer" 

>>> sqlTrans.save(sqlTransformerPath) 

>>> loadedSqlTrans = SQLTransformer.load(sqlTransformerPath) 

>>> loadedSqlTrans.getStatement() == sqlTrans.getStatement() 

True 

>>> loadedSqlTrans.transform(df).take(1) == sqlTrans.transform(df).take(1) 

True 

""" 

 

statement = Param(Params._dummy(), "statement", "SQL statement", 

typeConverter=TypeConverters.toString) 

 

@keyword_only 

def __init__(self, *, statement=None): 

""" 

__init__(self, \\*, statement=None) 

""" 

super(SQLTransformer, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.SQLTransformer", self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.6.0") 

def setParams(self, *, statement=None): 

""" 

setParams(self, \\*, statement=None) 

Sets params for this SQLTransformer. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("1.6.0") 

def setStatement(self, value): 

""" 

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

""" 

return self._set(statement=value) 

 

@since("1.6.0") 

def getStatement(self): 

""" 

Gets the value of statement or its default value. 

""" 

return self.getOrDefault(self.statement) 

 

 

class _StandardScalerParams(HasInputCol, HasOutputCol): 

""" 

Params for :py:class:`StandardScaler` and :py:class:`StandardScalerModel`. 

 

.. versionadded:: 3.0.0 

""" 

 

withMean = Param(Params._dummy(), "withMean", "Center data with mean", 

typeConverter=TypeConverters.toBoolean) 

withStd = Param(Params._dummy(), "withStd", "Scale to unit standard deviation", 

typeConverter=TypeConverters.toBoolean) 

 

def __init__(self, *args): 

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

self._setDefault(withMean=False, withStd=True) 

 

@since("1.4.0") 

def getWithMean(self): 

""" 

Gets the value of withMean or its default value. 

""" 

return self.getOrDefault(self.withMean) 

 

@since("1.4.0") 

def getWithStd(self): 

""" 

Gets the value of withStd or its default value. 

""" 

return self.getOrDefault(self.withStd) 

 

 

@inherit_doc 

class StandardScaler(JavaEstimator, _StandardScalerParams, JavaMLReadable, JavaMLWritable): 

""" 

Standardizes features by removing the mean and scaling to unit variance using column summary 

statistics on the samples in the training set. 

 

The "unit std" is computed using the `corrected sample standard deviation \ 

<https://en.wikipedia.org/wiki/Standard_deviation#Corrected_sample_standard_deviation>`_, 

which is computed as the square root of the unbiased sample variance. 

 

.. versionadded:: 1.4.0 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

>>> df = spark.createDataFrame([(Vectors.dense([0.0]),), (Vectors.dense([2.0]),)], ["a"]) 

>>> standardScaler = StandardScaler() 

>>> standardScaler.setInputCol("a") 

StandardScaler... 

>>> standardScaler.setOutputCol("scaled") 

StandardScaler... 

>>> model = standardScaler.fit(df) 

>>> model.getInputCol() 

'a' 

>>> model.setOutputCol("output") 

StandardScalerModel... 

>>> model.mean 

DenseVector([1.0]) 

>>> model.std 

DenseVector([1.4142]) 

>>> model.transform(df).collect()[1].output 

DenseVector([1.4142]) 

>>> standardScalerPath = temp_path + "/standard-scaler" 

>>> standardScaler.save(standardScalerPath) 

>>> loadedStandardScaler = StandardScaler.load(standardScalerPath) 

>>> loadedStandardScaler.getWithMean() == standardScaler.getWithMean() 

True 

>>> loadedStandardScaler.getWithStd() == standardScaler.getWithStd() 

True 

>>> modelPath = temp_path + "/standard-scaler-model" 

>>> model.save(modelPath) 

>>> loadedModel = StandardScalerModel.load(modelPath) 

>>> loadedModel.std == model.std 

True 

>>> loadedModel.mean == model.mean 

True 

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

True 

""" 

 

@keyword_only 

def __init__(self, *, withMean=False, withStd=True, inputCol=None, outputCol=None): 

""" 

__init__(self, \\*, withMean=False, withStd=True, inputCol=None, outputCol=None) 

""" 

super(StandardScaler, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.StandardScaler", self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.4.0") 

def setParams(self, *, withMean=False, withStd=True, inputCol=None, outputCol=None): 

""" 

setParams(self, \\*, withMean=False, withStd=True, inputCol=None, outputCol=None) 

Sets params for this StandardScaler. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("1.4.0") 

def setWithMean(self, value): 

""" 

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

""" 

return self._set(withMean=value) 

 

@since("1.4.0") 

def setWithStd(self, value): 

""" 

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

""" 

return self._set(withStd=value) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

def _create_model(self, java_model): 

return StandardScalerModel(java_model) 

 

 

class StandardScalerModel(JavaModel, _StandardScalerParams, JavaMLReadable, JavaMLWritable): 

""" 

Model fitted by :py:class:`StandardScaler`. 

 

.. versionadded:: 1.4.0 

""" 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

@property 

@since("2.0.0") 

def std(self): 

""" 

Standard deviation of the StandardScalerModel. 

""" 

return self._call_java("std") 

 

@property 

@since("2.0.0") 

def mean(self): 

""" 

Mean of the StandardScalerModel. 

""" 

return self._call_java("mean") 

 

 

class _StringIndexerParams(JavaParams, HasHandleInvalid, HasInputCol, HasOutputCol, 

HasInputCols, HasOutputCols): 

""" 

Params for :py:class:`StringIndexer` and :py:class:`StringIndexerModel`. 

""" 

 

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

"How to order labels of string column. The first label after " + 

"ordering is assigned an index of 0. Supported options: " + 

"frequencyDesc, frequencyAsc, alphabetDesc, alphabetAsc. " + 

"Default is frequencyDesc. In case of equal frequency when " + 

"under frequencyDesc/Asc, the strings are further sorted " + 

"alphabetically", 

typeConverter=TypeConverters.toString) 

 

handleInvalid = Param(Params._dummy(), "handleInvalid", "how to handle invalid data (unseen " + 

"or NULL values) in features and label column of string type. " + 

"Options are 'skip' (filter out rows with invalid data), " + 

"error (throw an error), or 'keep' (put invalid data " + 

"in a special additional bucket, at index numLabels).", 

typeConverter=TypeConverters.toString) 

 

def __init__(self, *args): 

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

self._setDefault(handleInvalid="error", stringOrderType="frequencyDesc") 

 

@since("2.3.0") 

def getStringOrderType(self): 

""" 

Gets the value of :py:attr:`stringOrderType` or its default value 'frequencyDesc'. 

""" 

return self.getOrDefault(self.stringOrderType) 

 

 

@inherit_doc 

class StringIndexer(JavaEstimator, _StringIndexerParams, JavaMLReadable, JavaMLWritable): 

""" 

A label indexer that maps a string column of labels to an ML column of label indices. 

If the input column is numeric, we cast it to string and index the string values. 

The indices are in [0, numLabels). By default, this is ordered by label frequencies 

so the most frequent label gets index 0. The ordering behavior is controlled by 

setting :py:attr:`stringOrderType`. Its default value is 'frequencyDesc'. 

 

.. versionadded:: 1.4.0 

 

Examples 

-------- 

>>> stringIndexer = StringIndexer(inputCol="label", outputCol="indexed", 

... stringOrderType="frequencyDesc") 

>>> stringIndexer.setHandleInvalid("error") 

StringIndexer... 

>>> model = stringIndexer.fit(stringIndDf) 

>>> model.setHandleInvalid("error") 

StringIndexerModel... 

>>> td = model.transform(stringIndDf) 

>>> sorted(set([(i[0], i[1]) for i in td.select(td.id, td.indexed).collect()]), 

... key=lambda x: x[0]) 

[(0, 0.0), (1, 2.0), (2, 1.0), (3, 0.0), (4, 0.0), (5, 1.0)] 

>>> inverter = IndexToString(inputCol="indexed", outputCol="label2", labels=model.labels) 

>>> itd = inverter.transform(td) 

>>> sorted(set([(i[0], str(i[1])) for i in itd.select(itd.id, itd.label2).collect()]), 

... key=lambda x: x[0]) 

[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'a'), (4, 'a'), (5, 'c')] 

>>> stringIndexerPath = temp_path + "/string-indexer" 

>>> stringIndexer.save(stringIndexerPath) 

>>> loadedIndexer = StringIndexer.load(stringIndexerPath) 

>>> loadedIndexer.getHandleInvalid() == stringIndexer.getHandleInvalid() 

True 

>>> modelPath = temp_path + "/string-indexer-model" 

>>> model.save(modelPath) 

>>> loadedModel = StringIndexerModel.load(modelPath) 

>>> loadedModel.labels == model.labels 

True 

>>> indexToStringPath = temp_path + "/index-to-string" 

>>> inverter.save(indexToStringPath) 

>>> loadedInverter = IndexToString.load(indexToStringPath) 

>>> loadedInverter.getLabels() == inverter.getLabels() 

True 

>>> loadedModel.transform(stringIndDf).take(1) == model.transform(stringIndDf).take(1) 

True 

>>> stringIndexer.getStringOrderType() 

'frequencyDesc' 

>>> stringIndexer = StringIndexer(inputCol="label", outputCol="indexed", handleInvalid="error", 

... stringOrderType="alphabetDesc") 

>>> model = stringIndexer.fit(stringIndDf) 

>>> td = model.transform(stringIndDf) 

>>> sorted(set([(i[0], i[1]) for i in td.select(td.id, td.indexed).collect()]), 

... key=lambda x: x[0]) 

[(0, 2.0), (1, 1.0), (2, 0.0), (3, 2.0), (4, 2.0), (5, 0.0)] 

>>> fromlabelsModel = StringIndexerModel.from_labels(["a", "b", "c"], 

... inputCol="label", outputCol="indexed", handleInvalid="error") 

>>> result = fromlabelsModel.transform(stringIndDf) 

>>> sorted(set([(i[0], i[1]) for i in result.select(result.id, result.indexed).collect()]), 

... key=lambda x: x[0]) 

[(0, 0.0), (1, 1.0), (2, 2.0), (3, 0.0), (4, 0.0), (5, 2.0)] 

>>> testData = sc.parallelize([Row(id=0, label1="a", label2="e"), 

... Row(id=1, label1="b", label2="f"), 

... Row(id=2, label1="c", label2="e"), 

... Row(id=3, label1="a", label2="f"), 

... Row(id=4, label1="a", label2="f"), 

... Row(id=5, label1="c", label2="f")], 3) 

>>> multiRowDf = spark.createDataFrame(testData) 

>>> inputs = ["label1", "label2"] 

>>> outputs = ["index1", "index2"] 

>>> stringIndexer = StringIndexer(inputCols=inputs, outputCols=outputs) 

>>> model = stringIndexer.fit(multiRowDf) 

>>> result = model.transform(multiRowDf) 

>>> sorted(set([(i[0], i[1], i[2]) for i in result.select(result.id, result.index1, 

... result.index2).collect()]), key=lambda x: x[0]) 

[(0, 0.0, 1.0), (1, 2.0, 0.0), (2, 1.0, 1.0), (3, 0.0, 0.0), (4, 0.0, 0.0), (5, 1.0, 0.0)] 

>>> fromlabelsModel = StringIndexerModel.from_arrays_of_labels([["a", "b", "c"], ["e", "f"]], 

... inputCols=inputs, outputCols=outputs) 

>>> result = fromlabelsModel.transform(multiRowDf) 

>>> sorted(set([(i[0], i[1], i[2]) for i in result.select(result.id, result.index1, 

... result.index2).collect()]), key=lambda x: x[0]) 

[(0, 0.0, 0.0), (1, 1.0, 1.0), (2, 2.0, 0.0), (3, 0.0, 1.0), (4, 0.0, 1.0), (5, 2.0, 1.0)] 

""" 

 

@keyword_only 

def __init__(self, *, inputCol=None, outputCol=None, inputCols=None, outputCols=None, 

handleInvalid="error", stringOrderType="frequencyDesc"): 

""" 

__init__(self, \\*, inputCol=None, outputCol=None, inputCols=None, outputCols=None, \ 

handleInvalid="error", stringOrderType="frequencyDesc") 

""" 

super(StringIndexer, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.StringIndexer", self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.4.0") 

def setParams(self, *, inputCol=None, outputCol=None, inputCols=None, outputCols=None, 

handleInvalid="error", stringOrderType="frequencyDesc"): 

""" 

setParams(self, \\*, inputCol=None, outputCol=None, inputCols=None, outputCols=None, \ 

handleInvalid="error", stringOrderType="frequencyDesc") 

Sets params for this StringIndexer. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

def _create_model(self, java_model): 

return StringIndexerModel(java_model) 

 

@since("2.3.0") 

def setStringOrderType(self, value): 

""" 

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

""" 

return self._set(stringOrderType=value) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

@since("3.0.0") 

def setInputCols(self, value): 

""" 

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

""" 

return self._set(inputCols=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

@since("3.0.0") 

def setOutputCols(self, value): 

""" 

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

""" 

return self._set(outputCols=value) 

 

def setHandleInvalid(self, value): 

""" 

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

""" 

return self._set(handleInvalid=value) 

 

 

class StringIndexerModel(JavaModel, _StringIndexerParams, JavaMLReadable, JavaMLWritable): 

""" 

Model fitted by :py:class:`StringIndexer`. 

 

.. versionadded:: 1.4.0 

""" 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

@since("3.0.0") 

def setInputCols(self, value): 

""" 

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

""" 

return self._set(inputCols=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

@since("3.0.0") 

def setOutputCols(self, value): 

""" 

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

""" 

return self._set(outputCols=value) 

 

@since("2.4.0") 

def setHandleInvalid(self, value): 

""" 

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

""" 

return self._set(handleInvalid=value) 

 

@classmethod 

@since("2.4.0") 

def from_labels(cls, labels, inputCol, outputCol=None, handleInvalid=None): 

""" 

Construct the model directly from an array of label strings, 

requires an active SparkContext. 

""" 

sc = SparkContext._active_spark_context 

java_class = sc._gateway.jvm.java.lang.String 

jlabels = StringIndexerModel._new_java_array(labels, java_class) 

model = StringIndexerModel._create_from_java_class( 

"org.apache.spark.ml.feature.StringIndexerModel", jlabels) 

model.setInputCol(inputCol) 

if outputCol is not None: 

model.setOutputCol(outputCol) 

if handleInvalid is not None: 

model.setHandleInvalid(handleInvalid) 

return model 

 

@classmethod 

@since("3.0.0") 

def from_arrays_of_labels(cls, arrayOfLabels, inputCols, outputCols=None, 

handleInvalid=None): 

""" 

Construct the model directly from an array of array of label strings, 

requires an active SparkContext. 

""" 

sc = SparkContext._active_spark_context 

java_class = sc._gateway.jvm.java.lang.String 

jlabels = StringIndexerModel._new_java_array(arrayOfLabels, java_class) 

model = StringIndexerModel._create_from_java_class( 

"org.apache.spark.ml.feature.StringIndexerModel", jlabels) 

model.setInputCols(inputCols) 

3843 ↛ 3845line 3843 didn't jump to line 3845, because the condition on line 3843 was never false if outputCols is not None: 

model.setOutputCols(outputCols) 

3845 ↛ 3846line 3845 didn't jump to line 3846, because the condition on line 3845 was never true if handleInvalid is not None: 

model.setHandleInvalid(handleInvalid) 

return model 

 

@property 

@since("1.5.0") 

def labels(self): 

""" 

Ordered list of labels, corresponding to indices to be assigned. 

 

.. deprecated:: 3.1.0 

It will be removed in future versions. Use `labelsArray` method instead. 

""" 

return self._call_java("labels") 

 

@property 

@since("3.0.2") 

def labelsArray(self): 

""" 

Array of ordered list of labels, corresponding to indices to be assigned 

for each input column. 

""" 

return self._call_java("labelsArray") 

 

 

@inherit_doc 

class IndexToString(JavaTransformer, HasInputCol, HasOutputCol, JavaMLReadable, JavaMLWritable): 

""" 

A :py:class:`pyspark.ml.base.Transformer` that maps a column of indices back to a new column of 

corresponding string values. 

The index-string mapping is either from the ML attributes of the input column, 

or from user-supplied labels (which take precedence over ML attributes). 

 

.. versionadded:: 1.6.0 

 

See Also 

-------- 

StringIndexer : for converting categorical values into category indices 

""" 

 

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

"Optional array of labels specifying index-string mapping." + 

" If not provided or if empty, then metadata from inputCol is used instead.", 

typeConverter=TypeConverters.toListString) 

 

@keyword_only 

def __init__(self, *, inputCol=None, outputCol=None, labels=None): 

""" 

__init__(self, \\*, inputCol=None, outputCol=None, labels=None) 

""" 

super(IndexToString, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.IndexToString", 

self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.6.0") 

def setParams(self, *, inputCol=None, outputCol=None, labels=None): 

""" 

setParams(self, \\*, inputCol=None, outputCol=None, labels=None) 

Sets params for this IndexToString. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("1.6.0") 

def setLabels(self, value): 

""" 

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

""" 

return self._set(labels=value) 

 

@since("1.6.0") 

def getLabels(self): 

""" 

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

""" 

return self.getOrDefault(self.labels) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

 

class StopWordsRemover(JavaTransformer, HasInputCol, HasOutputCol, HasInputCols, HasOutputCols, 

JavaMLReadable, JavaMLWritable): 

""" 

A feature transformer that filters out stop words from input. 

Since 3.0.0, :py:class:`StopWordsRemover` can filter out multiple columns at once by setting 

the :py:attr:`inputCols` parameter. Note that when both the :py:attr:`inputCol` and 

:py:attr:`inputCols` parameters are set, an Exception will be thrown. 

 

.. versionadded:: 1.6.0 

 

Notes 

----- 

null values from input array are preserved unless adding null to stopWords explicitly. 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(["a", "b", "c"],)], ["text"]) 

>>> remover = StopWordsRemover(stopWords=["b"]) 

>>> remover.setInputCol("text") 

StopWordsRemover... 

>>> remover.setOutputCol("words") 

StopWordsRemover... 

>>> remover.transform(df).head().words == ['a', 'c'] 

True 

>>> stopWordsRemoverPath = temp_path + "/stopwords-remover" 

>>> remover.save(stopWordsRemoverPath) 

>>> loadedRemover = StopWordsRemover.load(stopWordsRemoverPath) 

>>> loadedRemover.getStopWords() == remover.getStopWords() 

True 

>>> loadedRemover.getCaseSensitive() == remover.getCaseSensitive() 

True 

>>> loadedRemover.transform(df).take(1) == remover.transform(df).take(1) 

True 

>>> df2 = spark.createDataFrame([(["a", "b", "c"], ["a", "b"])], ["text1", "text2"]) 

>>> remover2 = StopWordsRemover(stopWords=["b"]) 

>>> remover2.setInputCols(["text1", "text2"]).setOutputCols(["words1", "words2"]) 

StopWordsRemover... 

>>> remover2.transform(df2).show() 

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

| text1| text2|words1|words2| 

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

|[a, b, c]|[a, b]|[a, c]| [a]| 

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

... 

""" 

 

stopWords = Param(Params._dummy(), "stopWords", "The words to be filtered out", 

typeConverter=TypeConverters.toListString) 

caseSensitive = Param(Params._dummy(), "caseSensitive", "whether to do a case sensitive " + 

"comparison over the stop words", typeConverter=TypeConverters.toBoolean) 

locale = Param(Params._dummy(), "locale", "locale of the input. ignored when case sensitive " + 

"is true", typeConverter=TypeConverters.toString) 

 

@keyword_only 

def __init__(self, *, inputCol=None, outputCol=None, stopWords=None, caseSensitive=False, 

locale=None, inputCols=None, outputCols=None): 

""" 

__init__(self, \\*, inputCol=None, outputCol=None, stopWords=None, caseSensitive=false, \ 

locale=None, inputCols=None, outputCols=None) 

""" 

super(StopWordsRemover, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.StopWordsRemover", 

self.uid) 

self._setDefault(stopWords=StopWordsRemover.loadDefaultStopWords("english"), 

caseSensitive=False, locale=self._java_obj.getLocale()) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.6.0") 

def setParams(self, *, inputCol=None, outputCol=None, stopWords=None, caseSensitive=False, 

locale=None, inputCols=None, outputCols=None): 

""" 

setParams(self, \\*, inputCol=None, outputCol=None, stopWords=None, caseSensitive=false, \ 

locale=None, inputCols=None, outputCols=None) 

Sets params for this StopWordRemover. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("1.6.0") 

def setStopWords(self, value): 

""" 

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

""" 

return self._set(stopWords=value) 

 

@since("1.6.0") 

def getStopWords(self): 

""" 

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

""" 

return self.getOrDefault(self.stopWords) 

 

@since("1.6.0") 

def setCaseSensitive(self, value): 

""" 

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

""" 

return self._set(caseSensitive=value) 

 

@since("1.6.0") 

def getCaseSensitive(self): 

""" 

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

""" 

return self.getOrDefault(self.caseSensitive) 

 

@since("2.4.0") 

def setLocale(self, value): 

""" 

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

""" 

return self._set(locale=value) 

 

@since("2.4.0") 

def getLocale(self): 

""" 

Gets the value of :py:attr:`locale`. 

""" 

return self.getOrDefault(self.locale) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

@since("3.0.0") 

def setInputCols(self, value): 

""" 

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

""" 

return self._set(inputCols=value) 

 

@since("3.0.0") 

def setOutputCols(self, value): 

""" 

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

""" 

return self._set(outputCols=value) 

 

@staticmethod 

@since("2.0.0") 

def loadDefaultStopWords(language): 

""" 

Loads the default stop words for the given language. 

Supported languages: danish, dutch, english, finnish, french, german, hungarian, 

italian, norwegian, portuguese, russian, spanish, swedish, turkish 

""" 

stopWordsObj = _jvm().org.apache.spark.ml.feature.StopWordsRemover 

return list(stopWordsObj.loadDefaultStopWords(language)) 

 

 

@inherit_doc 

class Tokenizer(JavaTransformer, HasInputCol, HasOutputCol, JavaMLReadable, JavaMLWritable): 

""" 

A tokenizer that converts the input string to lowercase and then 

splits it by white spaces. 

 

.. versionadded:: 1.3.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([("a b c",)], ["text"]) 

>>> tokenizer = Tokenizer(outputCol="words") 

>>> tokenizer.setInputCol("text") 

Tokenizer... 

>>> tokenizer.transform(df).head() 

Row(text='a b c', words=['a', 'b', 'c']) 

>>> # Change a parameter. 

>>> tokenizer.setParams(outputCol="tokens").transform(df).head() 

Row(text='a b c', tokens=['a', 'b', 'c']) 

>>> # Temporarily modify a parameter. 

>>> tokenizer.transform(df, {tokenizer.outputCol: "words"}).head() 

Row(text='a b c', words=['a', 'b', 'c']) 

>>> tokenizer.transform(df).head() 

Row(text='a b c', tokens=['a', 'b', 'c']) 

>>> # Must use keyword arguments to specify params. 

>>> tokenizer.setParams("text") 

Traceback (most recent call last): 

... 

TypeError: Method setParams forces keyword arguments. 

>>> tokenizerPath = temp_path + "/tokenizer" 

>>> tokenizer.save(tokenizerPath) 

>>> loadedTokenizer = Tokenizer.load(tokenizerPath) 

>>> loadedTokenizer.transform(df).head().tokens == tokenizer.transform(df).head().tokens 

True 

""" 

 

@keyword_only 

def __init__(self, *, inputCol=None, outputCol=None): 

""" 

__init__(self, \\*, inputCol=None, outputCol=None) 

""" 

super(Tokenizer, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.Tokenizer", self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.3.0") 

def setParams(self, *, inputCol=None, outputCol=None): 

""" 

setParams(self, \\*, inputCol=None, outputCol=None) 

Sets params for this Tokenizer. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

 

@inherit_doc 

class VectorAssembler(JavaTransformer, HasInputCols, HasOutputCol, HasHandleInvalid, JavaMLReadable, 

JavaMLWritable): 

""" 

A feature transformer that merges multiple columns into a vector column. 

 

.. versionadded:: 1.4.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(1, 0, 3)], ["a", "b", "c"]) 

>>> vecAssembler = VectorAssembler(outputCol="features") 

>>> vecAssembler.setInputCols(["a", "b", "c"]) 

VectorAssembler... 

>>> vecAssembler.transform(df).head().features 

DenseVector([1.0, 0.0, 3.0]) 

>>> vecAssembler.setParams(outputCol="freqs").transform(df).head().freqs 

DenseVector([1.0, 0.0, 3.0]) 

>>> params = {vecAssembler.inputCols: ["b", "a"], vecAssembler.outputCol: "vector"} 

>>> vecAssembler.transform(df, params).head().vector 

DenseVector([0.0, 1.0]) 

>>> vectorAssemblerPath = temp_path + "/vector-assembler" 

>>> vecAssembler.save(vectorAssemblerPath) 

>>> loadedAssembler = VectorAssembler.load(vectorAssemblerPath) 

>>> loadedAssembler.transform(df).head().freqs == vecAssembler.transform(df).head().freqs 

True 

>>> dfWithNullsAndNaNs = spark.createDataFrame( 

... [(1.0, 2.0, None), (3.0, float("nan"), 4.0), (5.0, 6.0, 7.0)], ["a", "b", "c"]) 

>>> vecAssembler2 = VectorAssembler(inputCols=["a", "b", "c"], outputCol="features", 

... handleInvalid="keep") 

>>> vecAssembler2.transform(dfWithNullsAndNaNs).show() 

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

| a| b| c| features| 

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

|1.0|2.0|null|[1.0,2.0,NaN]| 

|3.0|NaN| 4.0|[3.0,NaN,4.0]| 

|5.0|6.0| 7.0|[5.0,6.0,7.0]| 

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

... 

>>> vecAssembler2.setParams(handleInvalid="skip").transform(dfWithNullsAndNaNs).show() 

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

| a| b| c| features| 

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

|5.0|6.0|7.0|[5.0,6.0,7.0]| 

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

... 

""" 

 

handleInvalid = Param(Params._dummy(), "handleInvalid", "How to handle invalid data (NULL " + 

"and NaN values). Options are 'skip' (filter out rows with invalid " + 

"data), 'error' (throw an error), or 'keep' (return relevant number " + 

"of NaN in the output). Column lengths are taken from the size of ML " + 

"Attribute Group, which can be set using `VectorSizeHint` in a " + 

"pipeline before `VectorAssembler`. Column lengths can also be " + 

"inferred from first rows of the data since it is safe to do so but " + 

"only in case of 'error' or 'skip').", 

typeConverter=TypeConverters.toString) 

 

@keyword_only 

def __init__(self, *, inputCols=None, outputCol=None, handleInvalid="error"): 

""" 

__init__(self, \\*, inputCols=None, outputCol=None, handleInvalid="error") 

""" 

super(VectorAssembler, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.VectorAssembler", self.uid) 

self._setDefault(handleInvalid="error") 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.4.0") 

def setParams(self, *, inputCols=None, outputCol=None, handleInvalid="error"): 

""" 

setParams(self, \\*, inputCols=None, outputCol=None, handleInvalid="error") 

Sets params for this VectorAssembler. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

def setInputCols(self, value): 

""" 

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

""" 

return self._set(inputCols=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

def setHandleInvalid(self, value): 

""" 

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

""" 

return self._set(handleInvalid=value) 

 

 

class _VectorIndexerParams(HasInputCol, HasOutputCol, HasHandleInvalid): 

""" 

Params for :py:class:`VectorIndexer` and :py:class:`VectorIndexerModel`. 

 

.. versionadded:: 3.0.0 

""" 

 

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

"Threshold for the number of values a categorical feature can take " + 

"(>= 2). If a feature is found to have > maxCategories values, then " + 

"it is declared continuous.", typeConverter=TypeConverters.toInt) 

 

handleInvalid = Param(Params._dummy(), "handleInvalid", "How to handle invalid data " + 

"(unseen labels or NULL values). Options are 'skip' (filter out " + 

"rows with invalid data), 'error' (throw an error), or 'keep' (put " + 

"invalid data in a special additional bucket, at index of the number " + 

"of categories of the feature).", 

typeConverter=TypeConverters.toString) 

 

def __init__(self, *args): 

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

self._setDefault(maxCategories=20, handleInvalid="error") 

 

@since("1.4.0") 

def getMaxCategories(self): 

""" 

Gets the value of maxCategories or its default value. 

""" 

return self.getOrDefault(self.maxCategories) 

 

 

@inherit_doc 

class VectorIndexer(JavaEstimator, _VectorIndexerParams, JavaMLReadable, JavaMLWritable): 

""" 

Class for indexing categorical feature columns in a dataset of `Vector`. 

 

This has 2 usage modes: 

- Automatically identify categorical features (default behavior) 

- This helps process a dataset of unknown vectors into a dataset with some continuous 

features and some categorical features. The choice between continuous and categorical 

is based upon a maxCategories parameter. 

- Set maxCategories to the maximum number of categorical any categorical feature should 

have. 

- E.g.: Feature 0 has unique values {-1.0, 0.0}, and feature 1 values {1.0, 3.0, 5.0}. 

If maxCategories = 2, then feature 0 will be declared categorical and use indices {0, 1}, 

and feature 1 will be declared continuous. 

- Index all features, if all features are categorical 

- If maxCategories is set to be very large, then this will build an index of unique 

values for all features. 

- Warning: This can cause problems if features are continuous since this will collect ALL 

unique values to the driver. 

- E.g.: Feature 0 has unique values {-1.0, 0.0}, and feature 1 values {1.0, 3.0, 5.0}. 

If maxCategories >= 3, then both features will be declared categorical. 

 

This returns a model which can transform categorical features to use 0-based indices. 

 

Index stability: 

- This is not guaranteed to choose the same category index across multiple runs. 

- If a categorical feature includes value 0, then this is guaranteed to map value 0 to 

index 0. This maintains vector sparsity. 

- More stability may be added in the future. 

 

TODO: Future extensions: The following functionality is planned for the future: 

- Preserve metadata in transform; if a feature's metadata is already present, 

do not recompute. 

- Specify certain features to not index, either via a parameter or via existing metadata. 

- Add warning if a categorical feature has only 1 category. 

 

.. versionadded:: 1.4.0 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

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

... (Vectors.dense([0.0, 1.0]),), (Vectors.dense([0.0, 2.0]),)], ["a"]) 

>>> indexer = VectorIndexer(maxCategories=2, inputCol="a") 

>>> indexer.setOutputCol("indexed") 

VectorIndexer... 

>>> model = indexer.fit(df) 

>>> indexer.getHandleInvalid() 

'error' 

>>> model.setOutputCol("output") 

VectorIndexerModel... 

>>> model.transform(df).head().output 

DenseVector([1.0, 0.0]) 

>>> model.numFeatures 

2 

>>> model.categoryMaps 

{0: {0.0: 0, -1.0: 1}} 

>>> indexer.setParams(outputCol="test").fit(df).transform(df).collect()[1].test 

DenseVector([0.0, 1.0]) 

>>> params = {indexer.maxCategories: 3, indexer.outputCol: "vector"} 

>>> model2 = indexer.fit(df, params) 

>>> model2.transform(df).head().vector 

DenseVector([1.0, 0.0]) 

>>> vectorIndexerPath = temp_path + "/vector-indexer" 

>>> indexer.save(vectorIndexerPath) 

>>> loadedIndexer = VectorIndexer.load(vectorIndexerPath) 

>>> loadedIndexer.getMaxCategories() == indexer.getMaxCategories() 

True 

>>> modelPath = temp_path + "/vector-indexer-model" 

>>> model.save(modelPath) 

>>> loadedModel = VectorIndexerModel.load(modelPath) 

>>> loadedModel.numFeatures == model.numFeatures 

True 

>>> loadedModel.categoryMaps == model.categoryMaps 

True 

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

True 

>>> dfWithInvalid = spark.createDataFrame([(Vectors.dense([3.0, 1.0]),)], ["a"]) 

>>> indexer.getHandleInvalid() 

'error' 

>>> model3 = indexer.setHandleInvalid("skip").fit(df) 

>>> model3.transform(dfWithInvalid).count() 

0 

>>> model4 = indexer.setParams(handleInvalid="keep", outputCol="indexed").fit(df) 

>>> model4.transform(dfWithInvalid).head().indexed 

DenseVector([2.0, 1.0]) 

""" 

 

@keyword_only 

def __init__(self, *, maxCategories=20, inputCol=None, outputCol=None, handleInvalid="error"): 

""" 

__init__(self, \\*, maxCategories=20, inputCol=None, outputCol=None, handleInvalid="error") 

""" 

super(VectorIndexer, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.VectorIndexer", self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.4.0") 

def setParams(self, *, maxCategories=20, inputCol=None, outputCol=None, handleInvalid="error"): 

""" 

setParams(self, \\*, maxCategories=20, inputCol=None, outputCol=None, handleInvalid="error") 

Sets params for this VectorIndexer. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("1.4.0") 

def setMaxCategories(self, value): 

""" 

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

""" 

return self._set(maxCategories=value) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

def setHandleInvalid(self, value): 

""" 

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

""" 

return self._set(handleInvalid=value) 

 

def _create_model(self, java_model): 

return VectorIndexerModel(java_model) 

 

 

class VectorIndexerModel(JavaModel, _VectorIndexerParams, JavaMLReadable, JavaMLWritable): 

""" 

Model fitted by :py:class:`VectorIndexer`. 

 

Transform categorical features to use 0-based indices instead of their original values. 

- Categorical features are mapped to indices. 

- Continuous features (columns) are left unchanged. 

 

This also appends metadata to the output column, marking features as Numeric (continuous), 

Nominal (categorical), or Binary (either continuous or categorical). 

Non-ML metadata is not carried over from the input to the output column. 

 

This maintains vector sparsity. 

 

.. versionadded:: 1.4.0 

""" 

 

@since("3.0.0") 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

@since("3.0.0") 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

@property 

@since("1.4.0") 

def numFeatures(self): 

""" 

Number of features, i.e., length of Vectors which this transforms. 

""" 

return self._call_java("numFeatures") 

 

@property 

@since("1.4.0") 

def categoryMaps(self): 

""" 

Feature value index. Keys are categorical feature indices (column indices). 

Values are maps from original features values to 0-based category indices. 

If a feature is not in this map, it is treated as continuous. 

""" 

return self._call_java("javaCategoryMaps") 

 

 

@inherit_doc 

class VectorSlicer(JavaTransformer, HasInputCol, HasOutputCol, JavaMLReadable, JavaMLWritable): 

""" 

This class takes a feature vector and outputs a new feature vector with a subarray 

of the original features. 

 

The subset of features can be specified with either indices (`setIndices()`) 

or names (`setNames()`). At least one feature must be selected. Duplicate features 

are not allowed, so there can be no overlap between selected indices and names. 

 

The output vector will order features with the selected indices first (in the order given), 

followed by the selected names (in the order given). 

 

.. versionadded:: 1.6.0 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

>>> df = spark.createDataFrame([ 

... (Vectors.dense([-2.0, 2.3, 0.0, 0.0, 1.0]),), 

... (Vectors.dense([0.0, 0.0, 0.0, 0.0, 0.0]),), 

... (Vectors.dense([0.6, -1.1, -3.0, 4.5, 3.3]),)], ["features"]) 

>>> vs = VectorSlicer(outputCol="sliced", indices=[1, 4]) 

>>> vs.setInputCol("features") 

VectorSlicer... 

>>> vs.transform(df).head().sliced 

DenseVector([2.3, 1.0]) 

>>> vectorSlicerPath = temp_path + "/vector-slicer" 

>>> vs.save(vectorSlicerPath) 

>>> loadedVs = VectorSlicer.load(vectorSlicerPath) 

>>> loadedVs.getIndices() == vs.getIndices() 

True 

>>> loadedVs.getNames() == vs.getNames() 

True 

>>> loadedVs.transform(df).take(1) == vs.transform(df).take(1) 

True 

""" 

 

indices = Param(Params._dummy(), "indices", "An array of indices to select features from " + 

"a vector column. There can be no overlap with names.", 

typeConverter=TypeConverters.toListInt) 

names = Param(Params._dummy(), "names", "An array of feature names to select features from " + 

"a vector column. These names must be specified by ML " + 

"org.apache.spark.ml.attribute.Attribute. There can be no overlap with " + 

"indices.", typeConverter=TypeConverters.toListString) 

 

@keyword_only 

def __init__(self, *, inputCol=None, outputCol=None, indices=None, names=None): 

""" 

__init__(self, \\*, inputCol=None, outputCol=None, indices=None, names=None) 

""" 

super(VectorSlicer, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.VectorSlicer", self.uid) 

self._setDefault(indices=[], names=[]) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.6.0") 

def setParams(self, *, inputCol=None, outputCol=None, indices=None, names=None): 

""" 

setParams(self, \\*, inputCol=None, outputCol=None, indices=None, names=None): 

Sets params for this VectorSlicer. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("1.6.0") 

def setIndices(self, value): 

""" 

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

""" 

return self._set(indices=value) 

 

@since("1.6.0") 

def getIndices(self): 

""" 

Gets the value of indices or its default value. 

""" 

return self.getOrDefault(self.indices) 

 

@since("1.6.0") 

def setNames(self, value): 

""" 

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

""" 

return self._set(names=value) 

 

@since("1.6.0") 

def getNames(self): 

""" 

Gets the value of names or its default value. 

""" 

return self.getOrDefault(self.names) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

 

class _Word2VecParams(HasStepSize, HasMaxIter, HasSeed, HasInputCol, HasOutputCol): 

""" 

Params for :py:class:`Word2Vec` and :py:class:`Word2VecModel`. 

 

.. versionadded:: 3.0.0 

""" 

 

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

"the dimension of codes after transforming from words", 

typeConverter=TypeConverters.toInt) 

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

"number of partitions for sentences of words", 

typeConverter=TypeConverters.toInt) 

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

"the minimum number of times a token must appear to be included in the " + 

"word2vec model's vocabulary", typeConverter=TypeConverters.toInt) 

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

"the window size (context words from [-window, window]). Default value is 5", 

typeConverter=TypeConverters.toInt) 

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

"Maximum length (in words) of each sentence in the input data. " + 

"Any sentence longer than this threshold will " + 

"be divided into chunks up to the size.", 

typeConverter=TypeConverters.toInt) 

 

def __init__(self, *args): 

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

self._setDefault(vectorSize=100, minCount=5, numPartitions=1, stepSize=0.025, maxIter=1, 

windowSize=5, maxSentenceLength=1000) 

 

@since("1.4.0") 

def getVectorSize(self): 

""" 

Gets the value of vectorSize or its default value. 

""" 

return self.getOrDefault(self.vectorSize) 

 

@since("1.4.0") 

def getNumPartitions(self): 

""" 

Gets the value of numPartitions or its default value. 

""" 

return self.getOrDefault(self.numPartitions) 

 

@since("1.4.0") 

def getMinCount(self): 

""" 

Gets the value of minCount or its default value. 

""" 

return self.getOrDefault(self.minCount) 

 

@since("2.0.0") 

def getWindowSize(self): 

""" 

Gets the value of windowSize or its default value. 

""" 

return self.getOrDefault(self.windowSize) 

 

@since("2.0.0") 

def getMaxSentenceLength(self): 

""" 

Gets the value of maxSentenceLength or its default value. 

""" 

return self.getOrDefault(self.maxSentenceLength) 

 

 

@inherit_doc 

class Word2Vec(JavaEstimator, _Word2VecParams, JavaMLReadable, JavaMLWritable): 

""" 

Word2Vec trains a model of `Map(String, Vector)`, i.e. transforms a word into a code for further 

natural language processing or machine learning process. 

 

.. versionadded:: 1.4.0 

 

Examples 

-------- 

>>> sent = ("a b " * 100 + "a c " * 10).split(" ") 

>>> doc = spark.createDataFrame([(sent,), (sent,)], ["sentence"]) 

>>> word2Vec = Word2Vec(vectorSize=5, seed=42, inputCol="sentence", outputCol="model") 

>>> word2Vec.setMaxIter(10) 

Word2Vec... 

>>> word2Vec.getMaxIter() 

10 

>>> word2Vec.clear(word2Vec.maxIter) 

>>> model = word2Vec.fit(doc) 

>>> model.getMinCount() 

5 

>>> model.setInputCol("sentence") 

Word2VecModel... 

>>> model.getVectors().show() 

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

|word| vector| 

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

| a|[0.0951... 

| b|[-1.202... 

| c|[0.3015... 

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

... 

>>> model.findSynonymsArray("a", 2) 

[('b', 0.015859...), ('c', -0.568079...)] 

>>> from pyspark.sql.functions import format_number as fmt 

>>> model.findSynonyms("a", 2).select("word", fmt("similarity", 5).alias("similarity")).show() 

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

|word|similarity| 

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

| b| 0.01586| 

| c| -0.56808| 

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

... 

>>> model.transform(doc).head().model 

DenseVector([-0.4833, 0.1855, -0.273, -0.0509, -0.4769]) 

>>> word2vecPath = temp_path + "/word2vec" 

>>> word2Vec.save(word2vecPath) 

>>> loadedWord2Vec = Word2Vec.load(word2vecPath) 

>>> loadedWord2Vec.getVectorSize() == word2Vec.getVectorSize() 

True 

>>> loadedWord2Vec.getNumPartitions() == word2Vec.getNumPartitions() 

True 

>>> loadedWord2Vec.getMinCount() == word2Vec.getMinCount() 

True 

>>> modelPath = temp_path + "/word2vec-model" 

>>> model.save(modelPath) 

>>> loadedModel = Word2VecModel.load(modelPath) 

>>> loadedModel.getVectors().first().word == model.getVectors().first().word 

True 

>>> loadedModel.getVectors().first().vector == model.getVectors().first().vector 

True 

>>> loadedModel.transform(doc).take(1) == model.transform(doc).take(1) 

True 

""" 

 

@keyword_only 

def __init__(self, *, vectorSize=100, minCount=5, numPartitions=1, stepSize=0.025, 

maxIter=1, seed=None, inputCol=None, outputCol=None, windowSize=5, 

maxSentenceLength=1000): 

""" 

__init__(self, \\*, vectorSize=100, minCount=5, numPartitions=1, stepSize=0.025, \ 

maxIter=1, seed=None, inputCol=None, outputCol=None, windowSize=5, \ 

maxSentenceLength=1000) 

""" 

super(Word2Vec, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.Word2Vec", self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.4.0") 

def setParams(self, *, vectorSize=100, minCount=5, numPartitions=1, stepSize=0.025, 

maxIter=1, seed=None, inputCol=None, outputCol=None, windowSize=5, 

maxSentenceLength=1000): 

""" 

setParams(self, \\*, minCount=5, numPartitions=1, stepSize=0.025, maxIter=1, \ 

seed=None, inputCol=None, outputCol=None, windowSize=5, \ 

maxSentenceLength=1000) 

Sets params for this Word2Vec. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("1.4.0") 

def setVectorSize(self, value): 

""" 

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

""" 

return self._set(vectorSize=value) 

 

@since("1.4.0") 

def setNumPartitions(self, value): 

""" 

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

""" 

return self._set(numPartitions=value) 

 

@since("1.4.0") 

def setMinCount(self, value): 

""" 

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

""" 

return self._set(minCount=value) 

 

@since("2.0.0") 

def setWindowSize(self, value): 

""" 

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

""" 

return self._set(windowSize=value) 

 

@since("2.0.0") 

def setMaxSentenceLength(self, value): 

""" 

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

""" 

return self._set(maxSentenceLength=value) 

 

def setMaxIter(self, value): 

""" 

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

""" 

return self._set(maxIter=value) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

def setSeed(self, value): 

""" 

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

""" 

return self._set(seed=value) 

 

@since("1.4.0") 

def setStepSize(self, value): 

""" 

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

""" 

return self._set(stepSize=value) 

 

def _create_model(self, java_model): 

return Word2VecModel(java_model) 

 

 

class Word2VecModel(JavaModel, _Word2VecParams, JavaMLReadable, JavaMLWritable): 

""" 

Model fitted by :py:class:`Word2Vec`. 

 

.. versionadded:: 1.4.0 

""" 

 

@since("1.5.0") 

def getVectors(self): 

""" 

Returns the vector representation of the words as a dataframe 

with two fields, word and vector. 

""" 

return self._call_java("getVectors") 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

@since("1.5.0") 

def findSynonyms(self, word, num): 

""" 

Find "num" number of words closest in similarity to "word". 

word can be a string or vector representation. 

Returns a dataframe with two fields word and similarity (which 

gives the cosine similarity). 

""" 

4856 ↛ 4857line 4856 didn't jump to line 4857, because the condition on line 4856 was never true if not isinstance(word, str): 

word = _convert_to_vector(word) 

return self._call_java("findSynonyms", word, num) 

 

@since("2.3.0") 

def findSynonymsArray(self, word, num): 

""" 

Find "num" number of words closest in similarity to "word". 

word can be a string or vector representation. 

Returns an array with two fields word and similarity (which 

gives the cosine similarity). 

""" 

4868 ↛ 4869line 4868 didn't jump to line 4869, because the condition on line 4868 was never true if not isinstance(word, str): 

word = _convert_to_vector(word) 

tuples = self._java_obj.findSynonymsArray(word, num) 

return list(map(lambda st: (st._1(), st._2()), list(tuples))) 

 

 

class _PCAParams(HasInputCol, HasOutputCol): 

""" 

Params for :py:class:`PCA` and :py:class:`PCAModel`. 

 

.. versionadded:: 3.0.0 

""" 

 

k = Param(Params._dummy(), "k", "the number of principal components", 

typeConverter=TypeConverters.toInt) 

 

@since("1.5.0") 

def getK(self): 

""" 

Gets the value of k or its default value. 

""" 

return self.getOrDefault(self.k) 

 

 

@inherit_doc 

class PCA(JavaEstimator, _PCAParams, JavaMLReadable, JavaMLWritable): 

""" 

PCA trains a model to project vectors to a lower dimensional space of the 

top :py:attr:`k` principal components. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

>>> data = [(Vectors.sparse(5, [(1, 1.0), (3, 7.0)]),), 

... (Vectors.dense([2.0, 0.0, 3.0, 4.0, 5.0]),), 

... (Vectors.dense([4.0, 0.0, 0.0, 6.0, 7.0]),)] 

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

>>> pca = PCA(k=2, inputCol="features") 

>>> pca.setOutputCol("pca_features") 

PCA... 

>>> model = pca.fit(df) 

>>> model.getK() 

2 

>>> model.setOutputCol("output") 

PCAModel... 

>>> model.transform(df).collect()[0].output 

DenseVector([1.648..., -4.013...]) 

>>> model.explainedVariance 

DenseVector([0.794..., 0.205...]) 

>>> pcaPath = temp_path + "/pca" 

>>> pca.save(pcaPath) 

>>> loadedPca = PCA.load(pcaPath) 

>>> loadedPca.getK() == pca.getK() 

True 

>>> modelPath = temp_path + "/pca-model" 

>>> model.save(modelPath) 

>>> loadedModel = PCAModel.load(modelPath) 

>>> loadedModel.pc == model.pc 

True 

>>> loadedModel.explainedVariance == model.explainedVariance 

True 

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

True 

""" 

 

@keyword_only 

def __init__(self, *, k=None, inputCol=None, outputCol=None): 

""" 

__init__(self, \\*, k=None, inputCol=None, outputCol=None) 

""" 

super(PCA, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.PCA", self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.5.0") 

def setParams(self, *, k=None, inputCol=None, outputCol=None): 

""" 

setParams(self, \\*, k=None, inputCol=None, outputCol=None) 

Set params for this PCA. 

""" 

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) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

def _create_model(self, java_model): 

return PCAModel(java_model) 

 

 

class PCAModel(JavaModel, _PCAParams, JavaMLReadable, JavaMLWritable): 

""" 

Model fitted by :py:class:`PCA`. Transforms vectors to a lower dimensional space. 

 

.. versionadded:: 1.5.0 

""" 

 

@since("3.0.0") 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

@since("3.0.0") 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

@property 

@since("2.0.0") 

def pc(self): 

""" 

Returns a principal components Matrix. 

Each column is one principal component. 

""" 

return self._call_java("pc") 

 

@property 

@since("2.0.0") 

def explainedVariance(self): 

""" 

Returns a vector of proportions of variance 

explained by each principal component. 

""" 

return self._call_java("explainedVariance") 

 

 

class _RFormulaParams(HasFeaturesCol, HasLabelCol, HasHandleInvalid): 

""" 

Params for :py:class:`RFormula` and :py:class:`RFormula`. 

 

.. versionadded:: 3.0.0 

""" 

 

formula = Param(Params._dummy(), "formula", "R model formula", 

typeConverter=TypeConverters.toString) 

 

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

"Force to index label whether it is numeric or string", 

typeConverter=TypeConverters.toBoolean) 

 

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

"How to order categories of a string feature column used by " + 

"StringIndexer. The last category after ordering is dropped " + 

"when encoding strings. Supported options: frequencyDesc, " + 

"frequencyAsc, alphabetDesc, alphabetAsc. The default value " + 

"is frequencyDesc. When the ordering is set to alphabetDesc, " + 

"RFormula drops the same category as R when encoding strings.", 

typeConverter=TypeConverters.toString) 

 

handleInvalid = Param(Params._dummy(), "handleInvalid", "how to handle invalid entries. " + 

"Options are 'skip' (filter out rows with invalid values), " + 

"'error' (throw an error), or 'keep' (put invalid data in a special " + 

"additional bucket, at index numLabels).", 

typeConverter=TypeConverters.toString) 

 

def __init__(self, *args): 

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

self._setDefault(forceIndexLabel=False, stringIndexerOrderType="frequencyDesc", 

handleInvalid="error") 

 

@since("1.5.0") 

def getFormula(self): 

""" 

Gets the value of :py:attr:`formula`. 

""" 

return self.getOrDefault(self.formula) 

 

@since("2.1.0") 

def getForceIndexLabel(self): 

""" 

Gets the value of :py:attr:`forceIndexLabel`. 

""" 

return self.getOrDefault(self.forceIndexLabel) 

 

@since("2.3.0") 

def getStringIndexerOrderType(self): 

""" 

Gets the value of :py:attr:`stringIndexerOrderType` or its default value 'frequencyDesc'. 

""" 

return self.getOrDefault(self.stringIndexerOrderType) 

 

 

@inherit_doc 

class RFormula(JavaEstimator, _RFormulaParams, JavaMLReadable, JavaMLWritable): 

""" 

Implements the transforms required for fitting a dataset against an 

R model formula. Currently we support a limited subset of the R 

operators, including '~', '.', ':', '+', '-', '*', and '^'. 

 

.. versionadded:: 1.5.0 

 

Notes 

----- 

Also see the `R formula docs 

<http://stat.ethz.ch/R-manual/R-patched/library/stats/html/formula.html>`_. 

 

Examples 

-------- 

>>> df = spark.createDataFrame([ 

... (1.0, 1.0, "a"), 

... (0.0, 2.0, "b"), 

... (0.0, 0.0, "a") 

... ], ["y", "x", "s"]) 

>>> rf = RFormula(formula="y ~ x + s") 

>>> model = rf.fit(df) 

>>> model.getLabelCol() 

'label' 

>>> model.transform(df).show() 

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

| y| x| s| features|label| 

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

|1.0|1.0| a|[1.0,1.0]| 1.0| 

|0.0|2.0| b|[2.0,0.0]| 0.0| 

|0.0|0.0| a|[0.0,1.0]| 0.0| 

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

... 

>>> rf.fit(df, {rf.formula: "y ~ . - s"}).transform(df).show() 

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

| y| x| s|features|label| 

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

|1.0|1.0| a| [1.0]| 1.0| 

|0.0|2.0| b| [2.0]| 0.0| 

|0.0|0.0| a| [0.0]| 0.0| 

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

... 

>>> rFormulaPath = temp_path + "/rFormula" 

>>> rf.save(rFormulaPath) 

>>> loadedRF = RFormula.load(rFormulaPath) 

>>> loadedRF.getFormula() == rf.getFormula() 

True 

>>> loadedRF.getFeaturesCol() == rf.getFeaturesCol() 

True 

>>> loadedRF.getLabelCol() == rf.getLabelCol() 

True 

>>> loadedRF.getHandleInvalid() == rf.getHandleInvalid() 

True 

>>> str(loadedRF) 

'RFormula(y ~ x + s) (uid=...)' 

>>> modelPath = temp_path + "/rFormulaModel" 

>>> model.save(modelPath) 

>>> loadedModel = RFormulaModel.load(modelPath) 

>>> loadedModel.uid == model.uid 

True 

>>> loadedModel.transform(df).show() 

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

| y| x| s| features|label| 

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

|1.0|1.0| a|[1.0,1.0]| 1.0| 

|0.0|2.0| b|[2.0,0.0]| 0.0| 

|0.0|0.0| a|[0.0,1.0]| 0.0| 

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

... 

>>> str(loadedModel) 

'RFormulaModel(ResolvedRFormula(label=y, terms=[x,s], hasIntercept=true)) (uid=...)' 

""" 

 

@keyword_only 

def __init__(self, *, formula=None, featuresCol="features", labelCol="label", 

forceIndexLabel=False, stringIndexerOrderType="frequencyDesc", 

handleInvalid="error"): 

""" 

__init__(self, \\*, formula=None, featuresCol="features", labelCol="label", \ 

forceIndexLabel=False, stringIndexerOrderType="frequencyDesc", \ 

handleInvalid="error") 

""" 

super(RFormula, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.RFormula", self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("1.5.0") 

def setParams(self, *, formula=None, featuresCol="features", labelCol="label", 

forceIndexLabel=False, stringIndexerOrderType="frequencyDesc", 

handleInvalid="error"): 

""" 

setParams(self, \\*, formula=None, featuresCol="features", labelCol="label", \ 

forceIndexLabel=False, stringIndexerOrderType="frequencyDesc", \ 

handleInvalid="error") 

Sets params for RFormula. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("1.5.0") 

def setFormula(self, value): 

""" 

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

""" 

return self._set(formula=value) 

 

@since("2.1.0") 

def setForceIndexLabel(self, value): 

""" 

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

""" 

return self._set(forceIndexLabel=value) 

 

@since("2.3.0") 

def setStringIndexerOrderType(self, value): 

""" 

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

""" 

return self._set(stringIndexerOrderType=value) 

 

def setFeaturesCol(self, value): 

""" 

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

""" 

return self._set(featuresCol=value) 

 

def setLabelCol(self, value): 

""" 

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

""" 

return self._set(labelCol=value) 

 

def setHandleInvalid(self, value): 

""" 

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

""" 

return self._set(handleInvalid=value) 

 

def _create_model(self, java_model): 

return RFormulaModel(java_model) 

 

def __str__(self): 

formulaStr = self.getFormula() if self.isDefined(self.formula) else "" 

return "RFormula(%s) (uid=%s)" % (formulaStr, self.uid) 

 

 

class RFormulaModel(JavaModel, _RFormulaParams, JavaMLReadable, JavaMLWritable): 

""" 

Model fitted by :py:class:`RFormula`. Fitting is required to determine the 

factor levels of formula terms. 

 

.. versionadded:: 1.5.0 

""" 

 

def __str__(self): 

resolvedFormula = self._call_java("resolvedFormula") 

return "RFormulaModel(%s) (uid=%s)" % (resolvedFormula, self.uid) 

 

 

class _SelectorParams(HasFeaturesCol, HasOutputCol, HasLabelCol): 

""" 

Params for :py:class:`Selector` and :py:class:`SelectorModel`. 

 

.. versionadded:: 3.1.0 

""" 

 

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

"The selector type. " + 

"Supported options: numTopFeatures (default), percentile, fpr, fdr, fwe.", 

typeConverter=TypeConverters.toString) 

 

numTopFeatures = \ 

Param(Params._dummy(), "numTopFeatures", 

"Number of features that selector will select, ordered by ascending p-value. " + 

"If the number of features is < numTopFeatures, then this will select " + 

"all features.", typeConverter=TypeConverters.toInt) 

 

percentile = Param(Params._dummy(), "percentile", "Percentile of features that selector " + 

"will select, ordered by ascending p-value.", 

typeConverter=TypeConverters.toFloat) 

 

fpr = Param(Params._dummy(), "fpr", "The highest p-value for features to be kept.", 

typeConverter=TypeConverters.toFloat) 

 

fdr = Param(Params._dummy(), "fdr", "The upper bound of the expected false discovery rate.", 

typeConverter=TypeConverters.toFloat) 

 

fwe = Param(Params._dummy(), "fwe", "The upper bound of the expected family-wise error rate.", 

typeConverter=TypeConverters.toFloat) 

 

def __init__(self, *args): 

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

self._setDefault(numTopFeatures=50, selectorType="numTopFeatures", percentile=0.1, 

fpr=0.05, fdr=0.05, fwe=0.05) 

 

@since("2.1.0") 

def getSelectorType(self): 

""" 

Gets the value of selectorType or its default value. 

""" 

return self.getOrDefault(self.selectorType) 

 

@since("2.0.0") 

def getNumTopFeatures(self): 

""" 

Gets the value of numTopFeatures or its default value. 

""" 

return self.getOrDefault(self.numTopFeatures) 

 

@since("2.1.0") 

def getPercentile(self): 

""" 

Gets the value of percentile or its default value. 

""" 

return self.getOrDefault(self.percentile) 

 

@since("2.1.0") 

def getFpr(self): 

""" 

Gets the value of fpr or its default value. 

""" 

return self.getOrDefault(self.fpr) 

 

@since("2.2.0") 

def getFdr(self): 

""" 

Gets the value of fdr or its default value. 

""" 

return self.getOrDefault(self.fdr) 

 

@since("2.2.0") 

def getFwe(self): 

""" 

Gets the value of fwe or its default value. 

""" 

return self.getOrDefault(self.fwe) 

 

 

class _Selector(JavaEstimator, _SelectorParams, JavaMLReadable, JavaMLWritable): 

""" 

Mixin for Selectors. 

""" 

 

@since("2.1.0") 

def setSelectorType(self, value): 

""" 

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

""" 

return self._set(selectorType=value) 

 

@since("2.0.0") 

def setNumTopFeatures(self, value): 

""" 

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

Only applicable when selectorType = "numTopFeatures". 

""" 

return self._set(numTopFeatures=value) 

 

@since("2.1.0") 

def setPercentile(self, value): 

""" 

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

Only applicable when selectorType = "percentile". 

""" 

return self._set(percentile=value) 

 

@since("2.1.0") 

def setFpr(self, value): 

""" 

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

Only applicable when selectorType = "fpr". 

""" 

return self._set(fpr=value) 

 

@since("2.2.0") 

def setFdr(self, value): 

""" 

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

Only applicable when selectorType = "fdr". 

""" 

return self._set(fdr=value) 

 

@since("2.2.0") 

def setFwe(self, value): 

""" 

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

Only applicable when selectorType = "fwe". 

""" 

return self._set(fwe=value) 

 

def setFeaturesCol(self, value): 

""" 

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

""" 

return self._set(featuresCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

def setLabelCol(self, value): 

""" 

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

""" 

return self._set(labelCol=value) 

 

 

class _SelectorModel(JavaModel, _SelectorParams): 

""" 

Mixin for Selector models. 

""" 

 

@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 setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

@property 

@since("2.0.0") 

def selectedFeatures(self): 

""" 

List of indices to select (filter). 

""" 

return self._call_java("selectedFeatures") 

 

 

@inherit_doc 

class ChiSqSelector(_Selector, JavaMLReadable, JavaMLWritable): 

""" 

Chi-Squared feature selection, which selects categorical features to use for predicting a 

categorical label. 

The selector supports different selection methods: `numTopFeatures`, `percentile`, `fpr`, 

`fdr`, `fwe`. 

 

* `numTopFeatures` chooses a fixed number of top features according to a chi-squared test. 

 

* `percentile` is similar but chooses a fraction of all features 

instead of a fixed number. 

 

* `fpr` chooses all features whose p-values are below a threshold, 

thus controlling the false positive rate of selection. 

 

* `fdr` uses the `Benjamini-Hochberg procedure <https://en.wikipedia.org/wiki/ 

False_discovery_rate#Benjamini.E2.80.93Hochberg_procedure>`_ 

to choose all features whose false discovery rate is below a threshold. 

 

* `fwe` chooses all features whose p-values are below a threshold. The threshold is scaled by 

1/numFeatures, thus controlling the family-wise error rate of selection. 

 

By default, the selection method is `numTopFeatures`, with the default number of top features 

set to 50. 

 

.. deprecated:: 3.1.0 

Use UnivariateFeatureSelector 

 

.. versionadded:: 2.0.0 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

>>> df = spark.createDataFrame( 

... [(Vectors.dense([0.0, 0.0, 18.0, 1.0]), 1.0), 

... (Vectors.dense([0.0, 1.0, 12.0, 0.0]), 0.0), 

... (Vectors.dense([1.0, 0.0, 15.0, 0.1]), 0.0)], 

... ["features", "label"]) 

>>> selector = ChiSqSelector(numTopFeatures=1, outputCol="selectedFeatures") 

>>> model = selector.fit(df) 

>>> model.getFeaturesCol() 

'features' 

>>> model.setFeaturesCol("features") 

ChiSqSelectorModel... 

>>> model.transform(df).head().selectedFeatures 

DenseVector([18.0]) 

>>> model.selectedFeatures 

[2] 

>>> chiSqSelectorPath = temp_path + "/chi-sq-selector" 

>>> selector.save(chiSqSelectorPath) 

>>> loadedSelector = ChiSqSelector.load(chiSqSelectorPath) 

>>> loadedSelector.getNumTopFeatures() == selector.getNumTopFeatures() 

True 

>>> modelPath = temp_path + "/chi-sq-selector-model" 

>>> model.save(modelPath) 

>>> loadedModel = ChiSqSelectorModel.load(modelPath) 

>>> loadedModel.selectedFeatures == model.selectedFeatures 

True 

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

True 

""" 

 

@keyword_only 

def __init__(self, *, numTopFeatures=50, featuresCol="features", outputCol=None, 

labelCol="label", selectorType="numTopFeatures", percentile=0.1, fpr=0.05, 

fdr=0.05, fwe=0.05): 

""" 

__init__(self, \\*, numTopFeatures=50, featuresCol="features", outputCol=None, \ 

labelCol="label", selectorType="numTopFeatures", percentile=0.1, fpr=0.05, \ 

fdr=0.05, fwe=0.05) 

""" 

super(ChiSqSelector, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.ChiSqSelector", self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("2.0.0") 

def setParams(self, *, numTopFeatures=50, featuresCol="features", outputCol=None, 

labelCol="labels", selectorType="numTopFeatures", percentile=0.1, fpr=0.05, 

fdr=0.05, fwe=0.05): 

""" 

setParams(self, \\*, numTopFeatures=50, featuresCol="features", outputCol=None, \ 

labelCol="labels", selectorType="numTopFeatures", percentile=0.1, fpr=0.05, \ 

fdr=0.05, fwe=0.05) 

Sets params for this ChiSqSelector. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

def _create_model(self, java_model): 

return ChiSqSelectorModel(java_model) 

 

 

class ChiSqSelectorModel(_SelectorModel, JavaMLReadable, JavaMLWritable): 

""" 

Model fitted by :py:class:`ChiSqSelector`. 

 

.. versionadded:: 2.0.0 

""" 

 

 

@inherit_doc 

class VectorSizeHint(JavaTransformer, HasInputCol, HasHandleInvalid, JavaMLReadable, 

JavaMLWritable): 

""" 

A feature transformer that adds size information to the metadata of a vector column. 

VectorAssembler needs size information for its input columns and cannot be used on streaming 

dataframes without this metadata. 

 

.. versionadded:: 2.3.0 

 

Notes 

----- 

VectorSizeHint modifies `inputCol` to include size metadata and does not have an outputCol. 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

>>> from pyspark.ml import Pipeline, PipelineModel 

>>> data = [(Vectors.dense([1., 2., 3.]), 4.)] 

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

>>> 

>>> sizeHint = VectorSizeHint(inputCol="vector", size=3, handleInvalid="skip") 

>>> vecAssembler = VectorAssembler(inputCols=["vector", "float"], outputCol="assembled") 

>>> pipeline = Pipeline(stages=[sizeHint, vecAssembler]) 

>>> 

>>> pipelineModel = pipeline.fit(df) 

>>> pipelineModel.transform(df).head().assembled 

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

>>> vectorSizeHintPath = temp_path + "/vector-size-hint-pipeline" 

>>> pipelineModel.save(vectorSizeHintPath) 

>>> loadedPipeline = PipelineModel.load(vectorSizeHintPath) 

>>> loaded = loadedPipeline.transform(df).head().assembled 

>>> expected = pipelineModel.transform(df).head().assembled 

>>> loaded == expected 

True 

""" 

 

size = Param(Params._dummy(), "size", "Size of vectors in column.", 

typeConverter=TypeConverters.toInt) 

 

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

"How to handle invalid vectors in inputCol. Invalid vectors include " 

"nulls and vectors with the wrong size. The options are `skip` (filter " 

"out rows with invalid vectors), `error` (throw an error) and " 

"`optimistic` (do not check the vector size, and keep all rows). " 

"`error` by default.", 

TypeConverters.toString) 

 

@keyword_only 

def __init__(self, *, inputCol=None, size=None, handleInvalid="error"): 

""" 

__init__(self, \\*, inputCol=None, size=None, handleInvalid="error") 

""" 

super(VectorSizeHint, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.VectorSizeHint", self.uid) 

self._setDefault(handleInvalid="error") 

self.setParams(**self._input_kwargs) 

 

@keyword_only 

@since("2.3.0") 

def setParams(self, *, inputCol=None, size=None, handleInvalid="error"): 

""" 

setParams(self, \\*, inputCol=None, size=None, handleInvalid="error") 

Sets params for this VectorSizeHint. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("2.3.0") 

def getSize(self): 

""" Gets size param, the size of vectors in `inputCol`.""" 

return self.getOrDefault(self.size) 

 

@since("2.3.0") 

def setSize(self, value): 

""" Sets size param, the size of vectors in `inputCol`.""" 

return self._set(size=value) 

 

def setInputCol(self, value): 

""" 

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

""" 

return self._set(inputCol=value) 

 

def setHandleInvalid(self, value): 

""" 

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

""" 

return self._set(handleInvalid=value) 

 

 

class _VarianceThresholdSelectorParams(HasFeaturesCol, HasOutputCol): 

""" 

Params for :py:class:`VarianceThresholdSelector` and 

:py:class:`VarianceThresholdSelectorModel`. 

 

.. versionadded:: 3.1.0 

""" 

 

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

"Param for variance threshold. Features with a variance not " + 

"greater than this threshold will be removed. The default value " + 

"is 0.0.", typeConverter=TypeConverters.toFloat) 

 

@since("3.1.0") 

def getVarianceThreshold(self): 

""" 

Gets the value of varianceThreshold or its default value. 

""" 

return self.getOrDefault(self.varianceThreshold) 

 

 

@inherit_doc 

class VarianceThresholdSelector(JavaEstimator, _VarianceThresholdSelectorParams, JavaMLReadable, 

JavaMLWritable): 

""" 

Feature selector that removes all low-variance features. Features with a 

variance not greater than the threshold will be removed. The default is to keep 

all features with non-zero variance, i.e. remove the features that have the 

same value in all samples. 

 

.. versionadded:: 3.1.0 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

>>> df = spark.createDataFrame( 

... [(Vectors.dense([6.0, 7.0, 0.0, 7.0, 6.0, 0.0]),), 

... (Vectors.dense([0.0, 9.0, 6.0, 0.0, 5.0, 9.0]),), 

... (Vectors.dense([0.0, 9.0, 3.0, 0.0, 5.0, 5.0]),), 

... (Vectors.dense([0.0, 9.0, 8.0, 5.0, 6.0, 4.0]),), 

... (Vectors.dense([8.0, 9.0, 6.0, 5.0, 4.0, 4.0]),), 

... (Vectors.dense([8.0, 9.0, 6.0, 0.0, 0.0, 0.0]),)], 

... ["features"]) 

>>> selector = VarianceThresholdSelector(varianceThreshold=8.2, outputCol="selectedFeatures") 

>>> model = selector.fit(df) 

>>> model.getFeaturesCol() 

'features' 

>>> model.setFeaturesCol("features") 

VarianceThresholdSelectorModel... 

>>> model.transform(df).head().selectedFeatures 

DenseVector([6.0, 7.0, 0.0]) 

>>> model.selectedFeatures 

[0, 3, 5] 

>>> varianceThresholdSelectorPath = temp_path + "/variance-threshold-selector" 

>>> selector.save(varianceThresholdSelectorPath) 

>>> loadedSelector = VarianceThresholdSelector.load(varianceThresholdSelectorPath) 

>>> loadedSelector.getVarianceThreshold() == selector.getVarianceThreshold() 

True 

>>> modelPath = temp_path + "/variance-threshold-selector-model" 

>>> model.save(modelPath) 

>>> loadedModel = VarianceThresholdSelectorModel.load(modelPath) 

>>> loadedModel.selectedFeatures == model.selectedFeatures 

True 

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

True 

""" 

 

@keyword_only 

def __init__(self, *, featuresCol="features", outputCol=None, varianceThreshold=0.0): 

""" 

__init__(self, \\*, featuresCol="features", outputCol=None, varianceThreshold=0.0) 

""" 

super(VarianceThresholdSelector, self).__init__() 

self._java_obj = self._new_java_obj( 

"org.apache.spark.ml.feature.VarianceThresholdSelector", self.uid) 

self._setDefault(varianceThreshold=0.0) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("3.1.0") 

def setParams(self, *, featuresCol="features", outputCol=None, varianceThreshold=0.0): 

""" 

setParams(self, \\*, featuresCol="features", outputCol=None, varianceThreshold=0.0) 

Sets params for this VarianceThresholdSelector. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("3.1.0") 

def setVarianceThreshold(self, value): 

""" 

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

""" 

return self._set(varianceThreshold=value) 

 

@since("3.1.0") 

def setFeaturesCol(self, value): 

""" 

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

""" 

return self._set(featuresCol=value) 

 

@since("3.1.0") 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

def _create_model(self, java_model): 

return VarianceThresholdSelectorModel(java_model) 

 

 

class VarianceThresholdSelectorModel(JavaModel, _VarianceThresholdSelectorParams, JavaMLReadable, 

JavaMLWritable): 

""" 

Model fitted by :py:class:`VarianceThresholdSelector`. 

 

.. versionadded:: 3.1.0 

""" 

 

@since("3.1.0") 

def setFeaturesCol(self, value): 

""" 

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

""" 

return self._set(featuresCol=value) 

 

@since("3.1.0") 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

@property 

@since("3.1.0") 

def selectedFeatures(self): 

""" 

List of indices to select (filter). 

""" 

return self._call_java("selectedFeatures") 

 

 

class _UnivariateFeatureSelectorParams(HasFeaturesCol, HasOutputCol, HasLabelCol): 

""" 

Params for :py:class:`UnivariateFeatureSelector` and 

:py:class:`UnivariateFeatureSelectorModel`. 

 

.. versionadded:: 3.1.0 

""" 

 

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

"The feature type. " + 

"Supported options: categorical, continuous.", 

typeConverter=TypeConverters.toString) 

 

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

"The label type. " + 

"Supported options: categorical, continuous.", 

typeConverter=TypeConverters.toString) 

 

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

"The selection mode. " + 

"Supported options: numTopFeatures (default), percentile, fpr, " + 

"fdr, fwe.", 

typeConverter=TypeConverters.toString) 

 

selectionThreshold = Param(Params._dummy(), "selectionThreshold", "The upper bound of the " + 

"features that selector will select.", 

typeConverter=TypeConverters.toFloat) 

 

def __init__(self, *args): 

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

self._setDefault(selectionMode="numTopFeatures") 

 

@since("3.1.1") 

def getFeatureType(self): 

""" 

Gets the value of featureType or its default value. 

""" 

return self.getOrDefault(self.featureType) 

 

@since("3.1.1") 

def getLabelType(self): 

""" 

Gets the value of labelType or its default value. 

""" 

return self.getOrDefault(self.labelType) 

 

@since("3.1.1") 

def getSelectionMode(self): 

""" 

Gets the value of selectionMode or its default value. 

""" 

return self.getOrDefault(self.selectionMode) 

 

@since("3.1.1") 

def getSelectionThreshold(self): 

""" 

Gets the value of selectionThreshold or its default value. 

""" 

return self.getOrDefault(self.selectionThreshold) 

 

 

@inherit_doc 

class UnivariateFeatureSelector(JavaEstimator, _UnivariateFeatureSelectorParams, JavaMLReadable, 

JavaMLWritable): 

""" 

UnivariateFeatureSelector 

The user can set `featureType` and `labelType`, and Spark will pick the score function based on 

the specified `featureType` and `labelType`. 

 

The following combination of `featureType` and `labelType` are supported: 

 

- `featureType` `categorical` and `labelType` `categorical`, Spark uses chi-squared, 

i.e. chi2 in sklearn. 

- `featureType` `continuous` and `labelType` `categorical`, Spark uses ANOVATest, 

i.e. f_classif in sklearn. 

- `featureType` `continuous` and `labelType` `continuous`, Spark uses F-value, 

i.e. f_regression in sklearn. 

 

The `UnivariateFeatureSelector` supports different selection modes: `numTopFeatures`, 

`percentile`, `fpr`, `fdr`, `fwe`. 

 

- `numTopFeatures` chooses a fixed number of top features according to a according to a 

hypothesis. 

- `percentile` is similar but chooses a fraction of all features 

instead of a fixed number. 

- `fpr` chooses all features whose p-values are below a threshold, 

thus controlling the false positive rate of selection. 

- `fdr` uses the `Benjamini-Hochberg procedure \ 

<https://en.wikipedia.org/wiki/False_discovery_rate#Benjamini.E2.80.93Hochberg_procedure>`_ 

to choose all features whose false discovery rate is below a threshold. 

- `fwe` chooses all features whose p-values are below a threshold. The threshold is scaled by 

1 / `numFeatures`, thus controlling the family-wise error rate of selection. 

 

By default, the selection mode is `numTopFeatures`. 

 

.. versionadded:: 3.1.1 

 

Examples 

-------- 

>>> from pyspark.ml.linalg import Vectors 

>>> df = spark.createDataFrame( 

... [(Vectors.dense([1.7, 4.4, 7.6, 5.8, 9.6, 2.3]), 3.0), 

... (Vectors.dense([8.8, 7.3, 5.7, 7.3, 2.2, 4.1]), 2.0), 

... (Vectors.dense([1.2, 9.5, 2.5, 3.1, 8.7, 2.5]), 1.0), 

... (Vectors.dense([3.7, 9.2, 6.1, 4.1, 7.5, 3.8]), 2.0), 

... (Vectors.dense([8.9, 5.2, 7.8, 8.3, 5.2, 3.0]), 4.0), 

... (Vectors.dense([7.9, 8.5, 9.2, 4.0, 9.4, 2.1]), 4.0)], 

... ["features", "label"]) 

>>> selector = UnivariateFeatureSelector(outputCol="selectedFeatures") 

>>> selector.setFeatureType("continuous").setLabelType("categorical").setSelectionThreshold(1) 

UnivariateFeatureSelector... 

>>> model = selector.fit(df) 

>>> model.getFeaturesCol() 

'features' 

>>> model.setFeaturesCol("features") 

UnivariateFeatureSelectorModel... 

>>> model.transform(df).head().selectedFeatures 

DenseVector([7.6]) 

>>> model.selectedFeatures 

[2] 

>>> selectorPath = temp_path + "/selector" 

>>> selector.save(selectorPath) 

>>> loadedSelector = UnivariateFeatureSelector.load(selectorPath) 

>>> loadedSelector.getSelectionThreshold() == selector.getSelectionThreshold() 

True 

>>> modelPath = temp_path + "/selector-model" 

>>> model.save(modelPath) 

>>> loadedModel = UnivariateFeatureSelectorModel.load(modelPath) 

>>> loadedModel.selectedFeatures == model.selectedFeatures 

True 

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

True 

""" 

 

@keyword_only 

def __init__(self, *, featuresCol="features", outputCol=None, 

labelCol="label", selectionMode="numTopFeatures"): 

""" 

__init__(self, \\*, featuresCol="features", outputCol=None, \ 

labelCol="label", selectionMode="numTopFeatures") 

""" 

super(UnivariateFeatureSelector, self).__init__() 

self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.UnivariateFeatureSelector", 

self.uid) 

kwargs = self._input_kwargs 

self.setParams(**kwargs) 

 

@keyword_only 

@since("3.1.1") 

def setParams(self, *, featuresCol="features", outputCol=None, 

labelCol="labels", selectionMode="numTopFeatures"): 

""" 

setParams(self, \\*, featuresCol="features", outputCol=None, \ 

labelCol="labels", selectionMode="numTopFeatures") 

Sets params for this UnivariateFeatureSelector. 

""" 

kwargs = self._input_kwargs 

return self._set(**kwargs) 

 

@since("3.1.1") 

def setFeatureType(self, value): 

""" 

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

""" 

return self._set(featureType=value) 

 

@since("3.1.1") 

def setLabelType(self, value): 

""" 

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

""" 

return self._set(labelType=value) 

 

@since("3.1.1") 

def setSelectionMode(self, value): 

""" 

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

""" 

return self._set(selectionMode=value) 

 

@since("3.1.1") 

def setSelectionThreshold(self, value): 

""" 

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

""" 

return self._set(selectionThreshold=value) 

 

def setFeaturesCol(self, value): 

""" 

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

""" 

return self._set(featuresCol=value) 

 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

def setLabelCol(self, value): 

""" 

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

""" 

return self._set(labelCol=value) 

 

def _create_model(self, java_model): 

return UnivariateFeatureSelectorModel(java_model) 

 

 

class UnivariateFeatureSelectorModel(JavaModel, _UnivariateFeatureSelectorParams, JavaMLReadable, 

JavaMLWritable): 

""" 

Model fitted by :py:class:`UnivariateFeatureSelector`. 

 

.. versionadded:: 3.1.1 

""" 

 

@since("3.1.1") 

def setFeaturesCol(self, value): 

""" 

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

""" 

return self._set(featuresCol=value) 

 

@since("3.1.1") 

def setOutputCol(self, value): 

""" 

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

""" 

return self._set(outputCol=value) 

 

@property 

@since("3.1.1") 

def selectedFeatures(self): 

""" 

List of indices to select (filter). 

""" 

return self._call_java("selectedFeatures") 

 

 

if __name__ == "__main__": 

import doctest 

import sys 

import tempfile 

 

import pyspark.ml.feature 

from pyspark.sql import Row, SparkSession 

 

globs = globals().copy() 

features = pyspark.ml.feature.__dict__.copy() 

globs.update(features) 

 

# 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.feature tests")\ 

.getOrCreate() 

sc = spark.sparkContext 

globs['sc'] = sc 

globs['spark'] = spark 

testData = sc.parallelize([Row(id=0, label="a"), Row(id=1, label="b"), 

Row(id=2, label="c"), Row(id=3, label="a"), 

Row(id=4, label="a"), Row(id=5, label="c")], 2) 

globs['stringIndDf'] = spark.createDataFrame(testData) 

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 

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

sys.exit(-1)