text_plain_output_1.png
from sklearn.metrics import mean_absolute_error

from sklearn.tree import DecisionTreeRegressor

def get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y):
    model = DecisionTreeRegressor(max_leaf_nodes=max_leaf_nodes, random_state=0)
    model.fit(train_X, train_y)
    preds_val = model.predict(val_X)
    mae = mean_absolute_error(val_y, preds_val)
    return mae

candidate_max_leaf_nodes = [5, 25, 30, 40, 50, 100, 250, 500]
best_value = 0
controle = 0
for max_leaf_nodes in candidate_max_leaf_nodes:
    my_mae = get_mae(max_leaf_nodes, x_treino, x_teste, y_treino, y_teste)
    if best_value == 0:
        controle = my_mae
        best_value = max_leaf_nodes
    elif controle > my_mae:
        controle = my_mae
        best_value = max_leaf_nodes
best_tree_size = best_value
best_tree_size