This Decision Tree lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
A decision tree asks one yes or no question at a time and sends the row down a branch.
The example is a two-question tree for a pass mark. Real trees choose the questions from the data.
Start here
A very deep tree can memorize the training rows. Limit the depth.
def band(score, attendance): # define the function; it runs when you call it
if score < 70: # run the indented lines only when this is true
return "retry" # send this value back to the caller
if attendance < 75: # run the indented lines only when this is true
return "review" # send this value back to the caller
return "pass" # send this value back to the caller
print(band(82, 90))
Add two rows
Decision Tree applies one operation to every number. zip pairs the rows, and the list keeps each sum.
left = [1, 2, 12] # a list; the values stay in this order
right = [10, 20, 30] # a list; the values stay in this order
print([a + b for a, b in zip(left, right)]) # pair the lists, then combine each pair
Average a column
The average is the total divided by how many numbers you have. That is the same summary a statistics page starts with.
scores = [70, 12, 90] # a list; the values stay in this order
print(sum(scores) / len(scores)) # len counts the items
Keep values above a line
A cutoff drops the low values. Change 80 and run the example again to see who remains.
scores = [70, 12, 90] # a list; the values stay in this order
print([score for score in scores if score >= 80]) # keep the items that pass the test
