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

# 

# Licensed to the Apache Software Foundation (ASF) under one or more 

# contributor license agreements. See the NOTICE file distributed with 

# this work for additional information regarding copyright ownership. 

# The ASF licenses this file to You under the Apache License, Version 2.0 

# (the "License"); you may not use this file except in compliance with 

# the License. You may obtain a copy of the License at 

# 

# http://www.apache.org/licenses/LICENSE-2.0 

# 

# Unless required by applicable law or agreed to in writing, software 

# distributed under the License is distributed on an "AS IS" BASIS, 

# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

# See the License for the specific language governing permissions and 

# limitations under the License. 

# 

 

import sys 

import random 

 

from pyspark import RDD, since 

from pyspark.mllib.common import callMLlibFunc, inherit_doc, JavaModelWrapper 

from pyspark.mllib.linalg import _convert_to_vector 

from pyspark.mllib.regression import LabeledPoint 

from pyspark.mllib.util import JavaLoader, JavaSaveable 

 

__all__ = ['DecisionTreeModel', 'DecisionTree', 'RandomForestModel', 

'RandomForest', 'GradientBoostedTreesModel', 'GradientBoostedTrees'] 

 

 

class TreeEnsembleModel(JavaModelWrapper, JavaSaveable): 

"""TreeEnsembleModel 

 

.. versionadded:: 1.3.0 

""" 

def predict(self, x): 

""" 

Predict values for a single data point or an RDD of points using 

the model trained. 

 

.. versionadded:: 1.3.0 

 

Notes 

----- 

In Python, predict cannot currently be used within an RDD 

transformation or action. 

Call predict directly on the RDD instead. 

""" 

if isinstance(x, RDD): 

return self.call("predict", x.map(_convert_to_vector)) 

 

else: 

return self.call("predict", _convert_to_vector(x)) 

 

@since("1.3.0") 

def numTrees(self): 

""" 

Get number of trees in ensemble. 

""" 

return self.call("numTrees") 

 

@since("1.3.0") 

def totalNumNodes(self): 

""" 

Get total number of nodes, summed over all trees in the ensemble. 

""" 

return self.call("totalNumNodes") 

 

def __repr__(self): 

""" Summary of model """ 

return self._java_model.toString() 

 

@since("1.3.0") 

def toDebugString(self): 

""" Full model """ 

return self._java_model.toDebugString() 

 

 

class DecisionTreeModel(JavaModelWrapper, JavaSaveable, JavaLoader): 

""" 

A decision tree model for classification or regression. 

 

.. versionadded:: 1.1.0 

""" 

def predict(self, x): 

""" 

Predict the label of one or more examples. 

 

.. versionadded:: 1.1.0 

 

Parameters 

---------- 

x : :py:class:`pyspark.mllib.linalg.Vector` or :py:class:`pyspark.RDD` 

Data point (feature vector), or an RDD of data points (feature 

vectors). 

 

Notes 

----- 

In Python, predict cannot currently be used within an RDD 

transformation or action. 

Call predict directly on the RDD instead. 

""" 

if isinstance(x, RDD): 

return self.call("predict", x.map(_convert_to_vector)) 

 

else: 

return self.call("predict", _convert_to_vector(x)) 

 

@since("1.1.0") 

def numNodes(self): 

"""Get number of nodes in tree, including leaf nodes.""" 

return self._java_model.numNodes() 

 

@since("1.1.0") 

def depth(self): 

""" 

Get depth of tree (e.g. depth 0 means 1 leaf node, depth 1 

means 1 internal node + 2 leaf nodes). 

""" 

return self._java_model.depth() 

 

def __repr__(self): 

""" summary of model. """ 

return self._java_model.toString() 

 

@since("1.2.0") 

def toDebugString(self): 

""" full model. """ 

return self._java_model.toDebugString() 

 

@classmethod 

def _java_loader_class(cls): 

return "org.apache.spark.mllib.tree.model.DecisionTreeModel" 

 

 

class DecisionTree(object): 

""" 

Learning algorithm for a decision tree model for classification or 

regression. 

 

.. versionadded:: 1.1.0 

""" 

 

@classmethod 

def _train(cls, data, type, numClasses, features, impurity="gini", maxDepth=5, maxBins=32, 

minInstancesPerNode=1, minInfoGain=0.0): 

first = data.first() 

assert isinstance(first, LabeledPoint), "the data should be RDD of LabeledPoint" 

model = callMLlibFunc("trainDecisionTreeModel", data, type, numClasses, features, 

impurity, maxDepth, maxBins, minInstancesPerNode, minInfoGain) 

return DecisionTreeModel(model) 

 

@classmethod 

def trainClassifier(cls, data, numClasses, categoricalFeaturesInfo, 

impurity="gini", maxDepth=5, maxBins=32, minInstancesPerNode=1, 

minInfoGain=0.0): 

""" 

Train a decision tree model for classification. 

 

.. versionadded:: 1.1.0 

 

Parameters 

---------- 

data : :py:class:`pyspark.RDD` 

Training data: RDD of LabeledPoint. Labels should take values 

{0, 1, ..., numClasses-1}. 

numClasses : int 

Number of classes for classification. 

categoricalFeaturesInfo : dict 

Map storing arity of categorical features. An entry (n -> k) 

indicates that feature n is categorical with k categories 

indexed from 0: {0, 1, ..., k-1}. 

impurity : str, optional 

Criterion used for information gain calculation. 

Supported values: "gini" or "entropy". 

(default: "gini") 

maxDepth : int, optional 

Maximum depth of tree (e.g. depth 0 means 1 leaf node, depth 1 

means 1 internal node + 2 leaf nodes). 

(default: 5) 

maxBins : int, optional 

Number of bins used for finding splits at each node. 

(default: 32) 

minInstancesPerNode : int, optional 

Minimum number of instances required at child nodes to create 

the parent split. 

(default: 1) 

minInfoGain : float, optional 

Minimum info gain required to create a split. 

(default: 0.0) 

 

Returns 

------- 

:py:class:`DecisionTreeModel` 

 

Examples 

-------- 

>>> from numpy import array 

>>> from pyspark.mllib.regression import LabeledPoint 

>>> from pyspark.mllib.tree import DecisionTree 

>>> 

>>> data = [ 

... LabeledPoint(0.0, [0.0]), 

... LabeledPoint(1.0, [1.0]), 

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

... LabeledPoint(1.0, [3.0]) 

... ] 

>>> model = DecisionTree.trainClassifier(sc.parallelize(data), 2, {}) 

>>> print(model) 

DecisionTreeModel classifier of depth 1 with 3 nodes 

 

>>> print(model.toDebugString()) 

DecisionTreeModel classifier of depth 1 with 3 nodes 

If (feature 0 <= 0.5) 

Predict: 0.0 

Else (feature 0 > 0.5) 

Predict: 1.0 

<BLANKLINE> 

>>> model.predict(array([1.0])) 

1.0 

>>> model.predict(array([0.0])) 

0.0 

>>> rdd = sc.parallelize([[1.0], [0.0]]) 

>>> model.predict(rdd).collect() 

[1.0, 0.0] 

""" 

return cls._train(data, "classification", numClasses, categoricalFeaturesInfo, 

impurity, maxDepth, maxBins, minInstancesPerNode, minInfoGain) 

 

@classmethod 

@since("1.1.0") 

def trainRegressor(cls, data, categoricalFeaturesInfo, 

impurity="variance", maxDepth=5, maxBins=32, minInstancesPerNode=1, 

minInfoGain=0.0): 

""" 

Train a decision tree model for regression. 

 

Parameters 

---------- 

data : :py:class:`pyspark.RDD` 

Training data: RDD of LabeledPoint. Labels are real numbers. 

categoricalFeaturesInfo : dict 

Map storing arity of categorical features. An entry (n -> k) 

indicates that feature n is categorical with k categories 

indexed from 0: {0, 1, ..., k-1}. 

impurity : str, optional 

Criterion used for information gain calculation. 

The only supported value for regression is "variance". 

(default: "variance") 

maxDepth : int, optional 

Maximum depth of tree (e.g. depth 0 means 1 leaf node, depth 1 

means 1 internal node + 2 leaf nodes). 

(default: 5) 

maxBins : int, optional 

Number of bins used for finding splits at each node. 

(default: 32) 

minInstancesPerNode : int, optional 

Minimum number of instances required at child nodes to create 

the parent split. 

(default: 1) 

minInfoGain : float, optional 

Minimum info gain required to create a split. 

(default: 0.0) 

 

Returns 

------- 

:py:class:`DecisionTreeModel` 

 

Examples 

-------- 

>>> from pyspark.mllib.regression import LabeledPoint 

>>> from pyspark.mllib.tree import DecisionTree 

>>> from pyspark.mllib.linalg import SparseVector 

>>> 

>>> sparse_data = [ 

... LabeledPoint(0.0, SparseVector(2, {0: 0.0})), 

... LabeledPoint(1.0, SparseVector(2, {1: 1.0})), 

... LabeledPoint(0.0, SparseVector(2, {0: 0.0})), 

... LabeledPoint(1.0, SparseVector(2, {1: 2.0})) 

... ] 

>>> 

>>> model = DecisionTree.trainRegressor(sc.parallelize(sparse_data), {}) 

>>> model.predict(SparseVector(2, {1: 1.0})) 

1.0 

>>> model.predict(SparseVector(2, {1: 0.0})) 

0.0 

>>> rdd = sc.parallelize([[0.0, 1.0], [0.0, 0.0]]) 

>>> model.predict(rdd).collect() 

[1.0, 0.0] 

""" 

return cls._train(data, "regression", 0, categoricalFeaturesInfo, 

impurity, maxDepth, maxBins, minInstancesPerNode, minInfoGain) 

 

 

@inherit_doc 

class RandomForestModel(TreeEnsembleModel, JavaLoader): 

""" 

Represents a random forest model. 

 

.. versionadded:: 1.2.0 

""" 

 

@classmethod 

def _java_loader_class(cls): 

return "org.apache.spark.mllib.tree.model.RandomForestModel" 

 

 

class RandomForest(object): 

""" 

Learning algorithm for a random forest model for classification or 

regression. 

 

.. versionadded:: 1.2.0 

""" 

 

supportedFeatureSubsetStrategies = ("auto", "all", "sqrt", "log2", "onethird") 

 

@classmethod 

def _train(cls, data, algo, numClasses, categoricalFeaturesInfo, numTrees, 

featureSubsetStrategy, impurity, maxDepth, maxBins, seed): 

first = data.first() 

assert isinstance(first, LabeledPoint), "the data should be RDD of LabeledPoint" 

323 ↛ 324line 323 didn't jump to line 324, because the condition on line 323 was never true if featureSubsetStrategy not in cls.supportedFeatureSubsetStrategies: 

raise ValueError("unsupported featureSubsetStrategy: %s" % featureSubsetStrategy) 

325 ↛ 326line 325 didn't jump to line 326, because the condition on line 325 was never true if seed is None: 

seed = random.randint(0, 1 << 30) 

model = callMLlibFunc("trainRandomForestModel", data, algo, numClasses, 

categoricalFeaturesInfo, numTrees, featureSubsetStrategy, impurity, 

maxDepth, maxBins, seed) 

return RandomForestModel(model) 

 

@classmethod 

def trainClassifier(cls, data, numClasses, categoricalFeaturesInfo, numTrees, 

featureSubsetStrategy="auto", impurity="gini", maxDepth=4, maxBins=32, 

seed=None): 

""" 

Train a random forest model for binary or multiclass 

classification. 

 

.. versionadded:: 1.2.0 

 

Parameters 

---------- 

data : :py:class:`pyspark.RDD` 

Training dataset: RDD of LabeledPoint. Labels should take values 

{0, 1, ..., numClasses-1}. 

numClasses : int 

Number of classes for classification. 

categoricalFeaturesInfo : dict 

Map storing arity of categorical features. An entry (n -> k) 

indicates that feature n is categorical with k categories 

indexed from 0: {0, 1, ..., k-1}. 

numTrees : int 

Number of trees in the random forest. 

featureSubsetStrategy : str, optional 

Number of features to consider for splits at each node. 

Supported values: "auto", "all", "sqrt", "log2", "onethird". 

If "auto" is set, this parameter is set based on numTrees: 

if numTrees == 1, set to "all"; 

if numTrees > 1 (forest) set to "sqrt". 

(default: "auto") 

impurity : str, optional 

Criterion used for information gain calculation. 

Supported values: "gini" or "entropy". 

(default: "gini") 

maxDepth : int, optional 

Maximum depth of tree (e.g. depth 0 means 1 leaf node, depth 1 

means 1 internal node + 2 leaf nodes). 

(default: 4) 

maxBins : int, optional 

Maximum number of bins used for splitting features. 

(default: 32) 

seed : int, Optional 

Random seed for bootstrapping and choosing feature subsets. 

Set as None to generate seed based on system time. 

(default: None) 

 

Returns 

------- 

:py:class:`RandomForestModel` 

that can be used for prediction. 

 

Examples 

-------- 

>>> from pyspark.mllib.regression import LabeledPoint 

>>> from pyspark.mllib.tree import RandomForest 

>>> 

>>> data = [ 

... LabeledPoint(0.0, [0.0]), 

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

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

... LabeledPoint(1.0, [3.0]) 

... ] 

>>> model = RandomForest.trainClassifier(sc.parallelize(data), 2, {}, 3, seed=42) 

>>> model.numTrees() 

3 

>>> model.totalNumNodes() 

7 

>>> print(model) 

TreeEnsembleModel classifier with 3 trees 

<BLANKLINE> 

>>> print(model.toDebugString()) 

TreeEnsembleModel classifier with 3 trees 

<BLANKLINE> 

Tree 0: 

Predict: 1.0 

Tree 1: 

If (feature 0 <= 1.5) 

Predict: 0.0 

Else (feature 0 > 1.5) 

Predict: 1.0 

Tree 2: 

If (feature 0 <= 1.5) 

Predict: 0.0 

Else (feature 0 > 1.5) 

Predict: 1.0 

<BLANKLINE> 

>>> model.predict([2.0]) 

1.0 

>>> model.predict([0.0]) 

0.0 

>>> rdd = sc.parallelize([[3.0], [1.0]]) 

>>> model.predict(rdd).collect() 

[1.0, 0.0] 

""" 

return cls._train(data, "classification", numClasses, 

categoricalFeaturesInfo, numTrees, featureSubsetStrategy, impurity, 

maxDepth, maxBins, seed) 

 

@classmethod 

def trainRegressor(cls, data, categoricalFeaturesInfo, numTrees, featureSubsetStrategy="auto", 

impurity="variance", maxDepth=4, maxBins=32, seed=None): 

""" 

Train a random forest model for regression. 

 

.. versionadded:: 1.2.0 

 

Parameters 

---------- 

data : :py:class:`pyspark.RDD` 

Training dataset: RDD of LabeledPoint. Labels are real numbers. 

categoricalFeaturesInfo : dict 

Map storing arity of categorical features. An entry (n -> k) 

indicates that feature n is categorical with k categories 

indexed from 0: {0, 1, ..., k-1}. 

numTrees : int 

Number of trees in the random forest. 

featureSubsetStrategy : str, optional 

Number of features to consider for splits at each node. 

Supported values: "auto", "all", "sqrt", "log2", "onethird". 

If "auto" is set, this parameter is set based on numTrees: 

 

- if numTrees == 1, set to "all"; 

- if numTrees > 1 (forest) set to "onethird" for regression. 

 

(default: "auto") 

impurity : str, optional 

Criterion used for information gain calculation. 

The only supported value for regression is "variance". 

(default: "variance") 

maxDepth : int, optional 

Maximum depth of tree (e.g. depth 0 means 1 leaf node, depth 1 

means 1 internal node + 2 leaf nodes). 

(default: 4) 

maxBins : int, optional 

Maximum number of bins used for splitting features. 

(default: 32) 

seed : int, optional 

Random seed for bootstrapping and choosing feature subsets. 

Set as None to generate seed based on system time. 

(default: None) 

 

Returns 

------- 

:py:class:`RandomForestModel` 

that can be used for prediction. 

 

Examples 

-------- 

>>> from pyspark.mllib.regression import LabeledPoint 

>>> from pyspark.mllib.tree import RandomForest 

>>> from pyspark.mllib.linalg import SparseVector 

>>> 

>>> sparse_data = [ 

... LabeledPoint(0.0, SparseVector(2, {0: 1.0})), 

... LabeledPoint(1.0, SparseVector(2, {1: 1.0})), 

... LabeledPoint(0.0, SparseVector(2, {0: 1.0})), 

... LabeledPoint(1.0, SparseVector(2, {1: 2.0})) 

... ] 

>>> 

>>> model = RandomForest.trainRegressor(sc.parallelize(sparse_data), {}, 2, seed=42) 

>>> model.numTrees() 

2 

>>> model.totalNumNodes() 

4 

>>> model.predict(SparseVector(2, {1: 1.0})) 

1.0 

>>> model.predict(SparseVector(2, {0: 1.0})) 

0.5 

>>> rdd = sc.parallelize([[0.0, 1.0], [1.0, 0.0]]) 

>>> model.predict(rdd).collect() 

[1.0, 0.5] 

""" 

return cls._train(data, "regression", 0, categoricalFeaturesInfo, numTrees, 

featureSubsetStrategy, impurity, maxDepth, maxBins, seed) 

 

 

@inherit_doc 

class GradientBoostedTreesModel(TreeEnsembleModel, JavaLoader): 

""" 

Represents a gradient-boosted tree model. 

 

.. versionadded:: 1.3.0 

""" 

 

@classmethod 

def _java_loader_class(cls): 

return "org.apache.spark.mllib.tree.model.GradientBoostedTreesModel" 

 

 

class GradientBoostedTrees(object): 

""" 

Learning algorithm for a gradient boosted trees model for 

classification or regression. 

 

.. versionadded:: 1.3.0 

""" 

 

@classmethod 

def _train(cls, data, algo, categoricalFeaturesInfo, 

loss, numIterations, learningRate, maxDepth, maxBins): 

first = data.first() 

assert isinstance(first, LabeledPoint), "the data should be RDD of LabeledPoint" 

model = callMLlibFunc("trainGradientBoostedTreesModel", data, algo, categoricalFeaturesInfo, 

loss, numIterations, learningRate, maxDepth, maxBins) 

return GradientBoostedTreesModel(model) 

 

@classmethod 

def trainClassifier(cls, data, categoricalFeaturesInfo, 

loss="logLoss", numIterations=100, learningRate=0.1, maxDepth=3, 

maxBins=32): 

""" 

Train a gradient-boosted trees model for classification. 

 

.. versionadded:: 1.3.0 

 

Parameters 

---------- 

data : :py:class:`pyspark.RDD` 

Training dataset: RDD of LabeledPoint. Labels should take values 

{0, 1}. 

categoricalFeaturesInfo : dict 

Map storing arity of categorical features. An entry (n -> k) 

indicates that feature n is categorical with k categories 

indexed from 0: {0, 1, ..., k-1}. 

loss : str, optional 

Loss function used for minimization during gradient boosting. 

Supported values: "logLoss", "leastSquaresError", 

"leastAbsoluteError". 

(default: "logLoss") 

numIterations : int, optional 

Number of iterations of boosting. 

(default: 100) 

learningRate : float, optional 

Learning rate for shrinking the contribution of each estimator. 

The learning rate should be between in the interval (0, 1]. 

(default: 0.1) 

maxDepth : int, optional 

Maximum depth of tree (e.g. depth 0 means 1 leaf node, depth 1 

means 1 internal node + 2 leaf nodes). 

(default: 3) 

maxBins : int, optional 

Maximum number of bins used for splitting features. DecisionTree 

requires maxBins >= max categories. 

(default: 32) 

 

Returns 

------- 

:py:class:`GradientBoostedTreesModel` 

that can be used for prediction. 

 

Examples 

-------- 

>>> from pyspark.mllib.regression import LabeledPoint 

>>> from pyspark.mllib.tree import GradientBoostedTrees 

>>> 

>>> data = [ 

... LabeledPoint(0.0, [0.0]), 

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

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

... LabeledPoint(1.0, [3.0]) 

... ] 

>>> 

>>> model = GradientBoostedTrees.trainClassifier(sc.parallelize(data), {}, numIterations=10) 

>>> model.numTrees() 

10 

>>> model.totalNumNodes() 

30 

>>> print(model) # it already has newline 

TreeEnsembleModel classifier with 10 trees 

<BLANKLINE> 

>>> model.predict([2.0]) 

1.0 

>>> model.predict([0.0]) 

0.0 

>>> rdd = sc.parallelize([[2.0], [0.0]]) 

>>> model.predict(rdd).collect() 

[1.0, 0.0] 

""" 

return cls._train(data, "classification", categoricalFeaturesInfo, 

loss, numIterations, learningRate, maxDepth, maxBins) 

 

@classmethod 

def trainRegressor(cls, data, categoricalFeaturesInfo, 

loss="leastSquaresError", numIterations=100, learningRate=0.1, maxDepth=3, 

maxBins=32): 

""" 

Train a gradient-boosted trees model for regression. 

 

.. versionadded:: 1.3.0 

 

Parameters 

---------- 

data : 

Training dataset: RDD of LabeledPoint. Labels are real numbers. 

categoricalFeaturesInfo : dict 

Map storing arity of categorical features. An entry (n -> k) 

indicates that feature n is categorical with k categories 

indexed from 0: {0, 1, ..., k-1}. 

loss : str, optional 

Loss function used for minimization during gradient boosting. 

Supported values: "logLoss", "leastSquaresError", 

"leastAbsoluteError". 

(default: "leastSquaresError") 

numIterations : int, optional 

Number of iterations of boosting. 

(default: 100) 

learningRate : float, optional 

Learning rate for shrinking the contribution of each estimator. 

The learning rate should be between in the interval (0, 1]. 

(default: 0.1) 

maxDepth : int, optional 

Maximum depth of tree (e.g. depth 0 means 1 leaf node, depth 1 

means 1 internal node + 2 leaf nodes). 

(default: 3) 

maxBins : int, optional 

Maximum number of bins used for splitting features. DecisionTree 

requires maxBins >= max categories. 

(default: 32) 

 

Returns 

------- 

:py:class:`GradientBoostedTreesModel` 

that can be used for prediction. 

 

Examples 

-------- 

>>> from pyspark.mllib.regression import LabeledPoint 

>>> from pyspark.mllib.tree import GradientBoostedTrees 

>>> from pyspark.mllib.linalg import SparseVector 

>>> 

>>> sparse_data = [ 

... LabeledPoint(0.0, SparseVector(2, {0: 1.0})), 

... LabeledPoint(1.0, SparseVector(2, {1: 1.0})), 

... LabeledPoint(0.0, SparseVector(2, {0: 1.0})), 

... LabeledPoint(1.0, SparseVector(2, {1: 2.0})) 

... ] 

>>> 

>>> data = sc.parallelize(sparse_data) 

>>> model = GradientBoostedTrees.trainRegressor(data, {}, numIterations=10) 

>>> model.numTrees() 

10 

>>> model.totalNumNodes() 

12 

>>> model.predict(SparseVector(2, {1: 1.0})) 

1.0 

>>> model.predict(SparseVector(2, {0: 1.0})) 

0.0 

>>> rdd = sc.parallelize([[0.0, 1.0], [1.0, 0.0]]) 

>>> model.predict(rdd).collect() 

[1.0, 0.0] 

""" 

return cls._train(data, "regression", categoricalFeaturesInfo, 

loss, numIterations, learningRate, maxDepth, maxBins) 

 

 

def _test(): 

import doctest 

globs = globals().copy() 

from pyspark.sql import SparkSession 

spark = SparkSession.builder\ 

.master("local[4]")\ 

.appName("mllib.tree tests")\ 

.getOrCreate() 

globs['sc'] = spark.sparkContext 

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

spark.stop() 

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

sys.exit(-1) 

 

if __name__ == "__main__": 

_test()