28.1: Decision Trees in Python

The Crystal Ball - Instruction Manual I: Introduction to Data Science · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under not declared, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    28.1: Decision Trees in Python

    Our decision tree pictures from chapter 27 were quite illustrative, but of course to actually automate something, we have to write code rather than draw pictures. What would Figure 27.1 (p. 273) look like in Python code? It’s actually pretty simple, although there’s a lot of nested indentation. See if you can follow the flow in Figure 28.1.1.

    Here we’re defining a function called predict() that takes three arguments, one for each feature value. The eye-popping set of if/elif/else statements looks daunting at first, but when you scrutinize it you’ll realize it perfectly reflects the structure of the purple diagram. Each time we go down one level of the tree, we indent one tab to the right. The body of the “if major == 'PSYC':” statement is very short because the left-most branch of the tree (for Psychology) is very simple. The “elif major == 'CPSC':” body, by contrast, has lots of nested internal structure precisely because the right-most branch of the tree (for Computer Science) is complex. Etc.

    clipboard_e2000daebbdc77e6769be002f35295c57.png

    Figure \(\PageIndex(1)\): A Python implementation of the decision tree in Figure 27.2.1

    If we call this function, it will give us exactly the same predictions we calculated by hand on p. 273:

    Code \(\PageIndex{1}\) (Python):

    print(predict('PSYC','M','old'))

    print(predict('MATH','O','young'))

    print(predict('CPSC','F','old'))

    Output:

    | No

    | Yes

    | No


    This page titled 28.1: Decision Trees in Python was last modified on Sun, 18 Sep 2022 02:06:15 GMT and is shared under a not declared license and was authored, remixed, and/or curated by Stephen Davies (allthemath.org) via source content that was edited to the style and standards of the LibreTexts platform.