Skip to content

Commit 305e702

Browse files
committed
Extract decision_tree_predict().
1 parent ecc6b75 commit 305e702

File tree

1 file changed

+7
-11
lines changed

1 file changed

+7
-11
lines changed

learning.py

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -257,11 +257,8 @@ def __init__(self, attr, attrname=None, branches=None):
257257

258258
def predict(self, example):
259259
"Given an example, use the tree to classify the example."
260-
child = self.branches[example[self.attr]]
261-
if isinstance(child, DecisionTree):
262-
return child.predict(example)
263-
else:
264-
return child
260+
attrvalue = example[self.attr]
261+
return decision_tree_predict(self.branches[attrvalue], example)
265262

266263
def add(self, val, subtree):
267264
"Add a branch. If self.attr = val, go to the given subtree."
@@ -280,19 +277,18 @@ def display(self, indent=0):
280277
def __repr__(self):
281278
return ('DecisionTree(%r, %r, %r)'
282279
% (self.attr, self.attrname, self.branches))
283-
284-
Yes, No = True, False
280+
281+
def decision_tree_predict(tree, example):
282+
"Treat a non-DecisionTree as a leaf."
283+
return tree.predict(example) if isinstance(tree, DecisionTree) else tree
285284

286285
#______________________________________________________________________________
287286

288287
class DecisionTreeLearner(Learner):
289288
"[Fig. 18.5]"
290289

291290
def predict(self, example):
292-
if isinstance(self.dt, DecisionTree):
293-
return self.dt.predict(example)
294-
else:
295-
return self.dt
291+
return decision_tree_predict(self.dt, example)
296292

297293
def train(self, dataset):
298294
self.dataset = dataset

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy