26 KiB
26 KiB
In [1]:
import pandas as pd
viscosity_train = pd.read_csv("data/viscosity_train.csv", sep=";", decimal=",")
viscosity_test = pd.read_csv("data/viscosity_test.csv", sep=";", decimal=",")
display(viscosity_train.head(3))
display(viscosity_test.head(3))
In [2]:
viscosity_y_train = viscosity_train["Viscosity"]
viscosity_train = viscosity_train.drop(["Viscosity"], axis=1)
display(viscosity_train.head(3))
display(viscosity_y_train.head(3))
viscosity_y_test = viscosity_test["Viscosity"]
viscosity_test = viscosity_test.drop(["Viscosity"], axis=1)
display(viscosity_test.head(3))
display(viscosity_y_test.head(3))
In [3]:
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_model, tree, neighbors, ensemble
random_state = 9
models = {
"linear": {"model": linear_model.LinearRegression(n_jobs=-1)},
"linear_poly": {
"model": make_pipeline(
PolynomialFeatures(degree=2),
linear_model.LinearRegression(fit_intercept=False, n_jobs=-1),
)
},
"linear_interact": {
"model": make_pipeline(
PolynomialFeatures(interaction_only=True),
linear_model.LinearRegression(fit_intercept=False, n_jobs=-1),
)
},
"ridge": {"model": linear_model.RidgeCV()},
"decision_tree": {
"model": tree.DecisionTreeRegressor(max_depth=7, random_state=random_state)
},
"knn": {"model": neighbors.KNeighborsRegressor(n_neighbors=7, n_jobs=-1)},
"random_forest": {
"model": ensemble.RandomForestRegressor(
max_depth=7, random_state=random_state, n_jobs=-1
)
},
}
In [4]:
import math
from sklearn import metrics
for model_name in models.keys():
print(f"Model: {model_name}")
fitted_model = models[model_name]["model"].fit(
viscosity_train.values, viscosity_y_train.values.ravel()
)
y_train_pred = fitted_model.predict(viscosity_train.values)
y_test_pred = fitted_model.predict(viscosity_test.values)
models[model_name]["fitted"] = fitted_model
models[model_name]["train_preds"] = y_train_pred
models[model_name]["preds"] = y_test_pred
models[model_name]["RMSE_train"] = math.sqrt(
metrics.mean_squared_error(viscosity_y_train, y_train_pred)
)
models[model_name]["RMSE_test"] = math.sqrt(
metrics.mean_squared_error(viscosity_y_test, y_test_pred)
)
models[model_name]["RMAE_test"] = math.sqrt(
metrics.mean_absolute_error(viscosity_y_test, y_test_pred)
)
models[model_name]["R2_test"] = metrics.r2_score(viscosity_y_test, y_test_pred)
In [5]:
reg_metrics = pd.DataFrame.from_dict(models, "index")[
["RMSE_train", "RMSE_test", "RMAE_test", "R2_test"]
]
reg_metrics.sort_values(by="RMSE_test").style.background_gradient(
cmap="viridis", low=1, high=0.3, subset=["RMSE_train", "RMSE_test"]
).background_gradient(cmap="plasma", low=0.3, high=1, subset=["RMAE_test", "R2_test"])
Out[5]:
In [10]:
import numpy as np
from sklearn import model_selection
parameters = {
"criterion": ["squared_error", "absolute_error", "friedman_mse", "poisson"],
"max_depth": np.arange(1, 21).tolist()[0::2],
"min_samples_split": np.arange(2, 20).tolist()[0::2],
}
grid = model_selection.GridSearchCV(
tree.DecisionTreeRegressor(random_state=random_state), parameters, n_jobs=-1
)
grid.fit(viscosity_train, viscosity_y_train)
grid.best_params_
Out[10]:
In [11]:
model = grid.best_estimator_
y_pred = model.predict(viscosity_test)
old_metrics = {
"RMSE_test": models["decision_tree"]["RMSE_test"],
"RMAE_test": models["decision_tree"]["RMAE_test"],
"R2_test": models["decision_tree"]["R2_test"],
}
new_metrics = {}
new_metrics["RMSE_test"] = math.sqrt(
metrics.mean_squared_error(viscosity_y_test, y_pred)
)
new_metrics["RMAE_test"] = math.sqrt(
metrics.mean_absolute_error(viscosity_y_test, y_pred)
)
new_metrics["R2_test"] = metrics.r2_score(viscosity_y_test, y_pred)
display(old_metrics)
display(new_metrics)
In [12]:
rules = tree.export_text(
models["decision_tree"]["fitted"],
feature_names=viscosity_train.columns.values.tolist(),
)
print(rules)
In [13]:
import pickle
pickle.dump(models["decision_tree"]["fitted"], open("data/vtree.model.sav", "wb"))