def find_leaf(tree):
    leaf = {}
    #    print(tree)
    for key, value in tree.items():
        if value[7] == True:
            leaf[key] = value
    return leaf
def find_leaf(tree):
    leaf={}
    count=0
    for key,value in tree.items():
        if value[7]==True:
            leaf[key]=value
            count+=1
    return leaf,count
Exemple #3
0
def predict_example(x, tree):
    """
    Predicts the classification label for a single example x using tree by recursively descending the tree until
    a label/leaf node is reached.

    Returns the predicted label of x according to tree
    """

    if tree == 1 or tree == 0:  #terminate conditions if leaf node is reached
        return tree
    else:
        for i, j in tree.items():
            if ((i[1] == x[i[0]]) == i[2]):
                return predict_example(x, tree[i])
def predict_example(x, tree):
    """
    Predicts the classification label for a single example x using tree by recursively descending the tree until
    a label/leaf node is reached.

    Returns the predicted label of x according to tree
    """

    # INSERT YOUR CODE HERE. NOTE: THIS IS A RECURSIVE FUNCTION.
    for decision_node, child_tree in tree.items():
        idx = decision_node[0]
        val = decision_node[1]
        decision = decision_node[2]

        if decision == (x[idx] == val):
            if type(child_tree) is not dict:
                class_label = child_tree
            else:
                class_label = predict_example(x, child_tree)

            return class_label
def predict(x_test, tree_dict):
    result = []
    for i in x_test:
        try:
            (key, value), = tree_dict.items()
        except:
            result.append(tree_dict)
            continue

        tree = {}
        while type(value).__name__=='dict':
                if i[int(key)] <= value[2]:
                    tree = value[0]
                else:
                    tree = value[1]
                if type(tree).__name__=='int32' or type(tree).__name__=='int64':
                    result.append(tree)
                    break
                (key, value), = tree.items()

    return result
def predict_example(x, tree):
    """
    Predicts the classification label for a single example x using tree by recursively descending the tree until
    a label/leaf node is reached.

    Returns the predicted label of x according to tree
    """
    if (type(tree) is not dict):
        return tree
    # key = next(iter(tree))
    # if(key[2]==True):
    #     return predict_example(x,tree.get(key))
    # else:
    #     return predict_example(x,tree.get(next(iter(tree))))

    for key, subtree in tree.items():
        if (x[key[0]] == key[1]):
            if (key[2]):
                return predict_example(x, subtree)
        else:
            if (key[2] == False):
                return predict_example(x, subtree)