Building a decision tree from two lists

五迷三道 提交于 2019-12-11 16:45:05

问题


I'm trying to build this decision tree through two lists that I have.

input:

records= ['dead','healthy','cold','influenza']
symptoms= ['cough','sneezing','fever']

(doesn't always have to be this exact lists can be different lengths etc..)

the records list represent the leafs in the tree

output:

                                      cough
                      Yes /                            \ No
                   sneezing                        sneezing
               Yes /       \ No                Yes /       \ No
             fever         fever               fever         fever
       Yes /    \ No    Yes/     \No       Yes /    \ No    Yes/     \No
       dead   cold   influenza   cold      dead   influenza cold   healthy

my code:

def buildtree(symptoms,record):

    if len(record)==0:
        return Node(symptoms[0])
    else:
        withelt=buildtree(symptoms+[record[0]],record[1:])
        withoutelt=buildtree(symptoms,record[1:])
        here=Node(symptoms[0],withelt,withoutelt)
        return here

def get_leafs_from_records(records):

    optimal_illness = {}
    list_of_illnesses = []
    illness_in_records=[]
    for record in records:
        if diagnoser.diagnose(record.symptoms) == record.illness:
            list_of_illnesses.append(record.illness)

    for illness in list_of_illnesses:
        if illness in optimal_illness:
            optimal_illness[illness] += 1
        else:
            optimal_illness[illness] = 1

    for illness in optimal_illness:
        illness_in_records.append(illness)
    return illness_in_records

def build_tree(records, symptoms):

    records = get_leafs_from_records(records)

    return buildtree(symptoms,records)

the node class:

class Node:
    def __init__(self, data="", pos=None, neg=None):
       self.data = data
       self.positive_child = pos
       self.negative_child = neg

my get_leafs_from_records(records) function is just to make it as list that i i put input in the start u can ignore it.

My code is not working as it supposed its not building the tree like its supposed It keeps building just the first node any ideas?

If anything else is unclear please let me know.

来源:https://stackoverflow.com/questions/48061939/building-a-decision-tree-from-two-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!