What is wrong in this code to get number of leaf nodes for minimum mean absolute error

Viewed 58

I have to use a for loop to cycle through mean_absolute_errors for the list of leaf nodes and get the number of nodes for minimum value of get_mae(). This is from the Kaggle "Intro to Machine Learning" tutorial.

candidate_max_leaf_nodes = [5, 25, 50, 100, 250, 500]
# Write loop to find the ideal tree size from candidate_max_leaf_nodes
_
min = get_mae(candidate_max_leaf_nodes[0], train_X, val_X, train_y, val_y)
nodes = 0
for max_leaf_nodes in candidate_max_leaf_nodes:
    my_mae = get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y)
    if my_mae < min:
        nodes = max_leaf_nodes

# Store the best value of max_leaf_nodes (it will be either 5, 25, 50, 100, 250 or 500)
best_tree_size = nodes

# Check your answer
step_1.check()

My answer is coming as 500 and it is not the correct answer.

1 Answers

I think the minimum value logic needs to be corrected. When a minimum value is found, it should update the min_val. Please note to avoid min as a variable as it is a python reserved word.

candidate_max_leaf_nodes = [25, 50, 100, 250, 500]

min_val = get_mae(5, train_X, val_X, train_y, val_y)
nodes = 0

for max_leaf_nodes in candidate_max_leaf_nodes:
    my_mae = get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y)
    if my_mae < min_val:
        min_val = my_mae
        nodes = max_leaf_nodes
Related