10. Python - Data Analytics - Scikit-Learn

MODEL VALIDATION:

Splitting Data with Scikit_Learn:

from sklearn.model_selection import train_test_split

train_X, val_X, train_y, val_y = train_test_split(X, y, random_state = 0)

// splits data into training and validation data. must define X and y beforehand, which is the features and the prediction.

melbourne_model.fit(train_X, train_y)

# get predicted prices on validation data

val_predictions = melbourne_model.predict(val_X)

print(mean_absolute_error(val_y, val_predictions))


Calculating MAE (Mean Absolute Error):

from sklearn.metrics import mean_absolute_error

predicted_home_prices = melbourne_model.predict(X)

mean_absolute_error(y, predicted_home_prices)

// MAE is the sum average of all absolute difference between the actual and the prediction value.


Overfitting and Underfitting:

// Overfitting is too many leaves in decision tree. Might seem like it gets accurate prediction but it becomes far off when using new data to predict.

// Underfitting is too few leaves in decision tree. This makes decision tree too broad and doesn't capture many distinctions. Not accurate.

// To find best balance. Find the sweet spot in number of leaves to use that generate lowest MAE.


Create a function to use different types of leaf nodes:

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)


Print and compare leave node options and their MAE results:

# compare MAE with differing values of max_leaf_nodes

for max_leaf_nodes in [5, 50, 500, 5000]:

    my_mae = get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y)

    print("Max leaf nodes: %d  \t\t Mean Absolute Error:  %d" %(max_leaf_nodes, my_mae))


// after knowing the best leaf node amount. We can refit a new model using all the original X and y data and not use train_X or train_y

Comments

Popular posts from this blog

2. FreeCodeCamp - Dynamic Programming - Learn to Solve Algorithmic Problems & Coding Challenges

20. Data Analytics - Analyze Data to Answer Questions - Week 1

3. Algorithms - Selection Sort