<jupyter_start><jupyter_text>Especificando alvo para predição<jupyter_code>df.columns
y = df.SalePrice
y.describe()
y.shape<jupyter_output><empty_output><jupyter_text>Criando as Features* LotArea* YearBuilt* 1stFlrSF* 2ndFlrSF* FullBath* BedroomAbvGr* TotRmsAbvGrd<jupyter_code>features = 'LotArea YearBuilt 1stFlrSF 2ndFlrSF FullBath BedroomAbvGr TotRmsAbvGrd'.split()
features
X = df[features]
print('Imprimindo as 5 primeiras linhas de X')
X.head()
print('Descrição ou Estatística de X')
X.describe()
X.shape<jupyter_output><empty_output><jupyter_text>Criando um Modelo<jupyter_code>from sklearn.tree import DecisionTreeRegressor
iowa_model = DecisionTreeRegressor(random_state=1)

iowa_model.fit(X, y)<jupyter_output><empty_output><jupyter_text>Fazendo Predições<jupyter_code>predictions = iowa_model.predict(X.head())

print('Predições:\n')
for p in predictions:
    print(p)<jupyter_output>Predições:

208500.0
181500.0
223500.0
140000.0
250000.0<jupyter_text>Comparando os resultados<jupyter_code>y.head()<jupyter_output><empty_output><jupyter_text>Validando o Modelo<jupyter_code>from sklearn.model_selection import train_test_split
train_X, val_X, train_y, val_y = train_test_split(X, y, random_state = 1)

iowa_model = DecisionTreeRegressor(random_state = 1)

iowa_model.fit(train_X, train_y)
print(f'{train_X.shape}\t{train_y.shape}\t\t{val_X.shape}\t{val_y.shape}')
val_predictions = iowa_model.predict(val_X)

print(val_predictions[0:5])

print(y.head().tolist())<jupyter_output>[186500. 184000. 130000.  92000. 164500.]
[208500, 181500, 223500, 140000, 250000]<jupyter_text>Calculando o Erro Médio Absoluto<jupyter_code>from sklearn.metrics import mean_absolute_error
val_mae = mean_absolute_error(val_predictions, val_y)

print(val_mae)<jupyter_output>29652.931506849316<jupyter_text>Na descrição estatística da coluna alvo que são os valores de venda dos imóveis (y.describe()), o valor médio de venda dos imóveis é de 180.921.O valor de erro médio absoluto é de 29.652, o que dá em torno de 16% do valor médio de venda. Em tese o modelo estaria com acerto de previsão em 84%.  Comparando os diferentes tamanhos de nós<jupyter_code>def get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y):
    model = DecisionTreeRegressor(max_leaf_nodes=max_leaf_nodes, random_state=1)
    model.fit(train_X, train_y)
    preds_val = model.predict(val_X)
    mae = mean_absolute_error(val_y, preds_val)
    return mae
nodes = [5, 25, 50, 100, 250]

for max_leaf_nodes in nodes:
    my_mae = get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y)
    print('Max leaf nodes: {} \t\t Mean Absolute Error: {:.0f}'.format(max_leaf_nodes, my_mae))
best_tree_size = 100

final_model = DecisionTreeRegressor(max_leaf_nodes=best_tree_size, random_state=1)

final_model.fit(X, y)
predictions = final_model.predict(X.head())

print('Predições: \n')
for p in predictions:
    print(f'{p:.0f}')
# Comparando

y.head()<jupyter_output><empty_output>