fuzzy-rules-generator/density_regression.ipynb
2024-11-01 11:04:05 +04:00

26 KiB

In [2]:
import pandas as pd

density_train = pd.read_csv("data/density_train.csv", sep=";", decimal=",")
density_test = pd.read_csv("data/density_test.csv", sep=";", decimal=",")

display(density_train.head(3))
display(density_test.head(3))
T Al2O3 TiO2 Density
0 20 0.0 0.0 1.06250
1 25 0.0 0.0 1.05979
2 35 0.0 0.0 1.05404
T Al2O3 TiO2 Density
0 30 0.00 0.0 1.05696
1 55 0.00 0.0 1.04158
2 25 0.05 0.0 1.08438
In [3]:
density_y_train = density_train["Density"]
density_train = density_train.drop(["Density"], axis=1)

display(density_train.head(3))
display(density_y_train.head(3))

density_y_test = density_test["Density"]
density_test = density_test.drop(["Density"], axis=1)

display(density_test.head(3))
display(density_y_test.head(3))
T Al2O3 TiO2
0 20 0.0 0.0
1 25 0.0 0.0
2 35 0.0 0.0
0    1.06250
1    1.05979
2    1.05404
Name: Density, dtype: float64
T Al2O3 TiO2
0 30 0.00 0.0
1 55 0.00 0.0
2 25 0.05 0.0
0    1.05696
1    1.04158
2    1.08438
Name: Density, dtype: float64
In [4]:
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 [5]:
import math
from sklearn import metrics

for model_name in models.keys():
    print(f"Model: {model_name}")
    fitted_model = models[model_name]["model"].fit(
        density_train.values, density_y_train.values.ravel()
    )
    y_train_pred = fitted_model.predict(density_train.values)
    y_test_pred = fitted_model.predict(density_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(density_y_train, y_train_pred)
    )
    models[model_name]["RMSE_test"] = math.sqrt(
        metrics.mean_squared_error(density_y_test, y_test_pred)
    )
    models[model_name]["RMAE_test"] = math.sqrt(
        metrics.mean_absolute_error(density_y_test, y_test_pred)
    )
    models[model_name]["R2_test"] = metrics.r2_score(density_y_test, y_test_pred)
Model: linear
Model: linear_poly
Model: linear_interact
Model: ridge
Model: decision_tree
Model: knn
Model: random_forest
In [6]:
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[6]:
  RMSE_train RMSE_test RMAE_test R2_test
linear_poly 0.000319 0.000362 0.016643 0.999965
linear_interact 0.001131 0.001491 0.033198 0.999413
linear 0.002464 0.003261 0.049891 0.997191
random_forest 0.002716 0.005575 0.067298 0.991788
decision_tree 0.000346 0.006433 0.076138 0.989067
ridge 0.013989 0.015356 0.116380 0.937703
knn 0.053108 0.056776 0.217611 0.148414
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, 11).tolist()[0::2],
}

grid = model_selection.GridSearchCV(
    tree.DecisionTreeRegressor(random_state=random_state), parameters, n_jobs=-1
)

grid.fit(density_train, density_y_train)
grid.best_params_
c:\Users\user\Projects\python\fuzzy\.venv\Lib\site-packages\numpy\ma\core.py:2881: RuntimeWarning: invalid value encountered in cast
  _data = np.array(data, dtype=dtype, copy=copy,
Out[10]:
{'criterion': 'absolute_error', 'max_depth': 7}
In [11]:
model = grid.best_estimator_
y_pred = model.predict(density_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(density_y_test, y_pred))
new_metrics["RMAE_test"] = math.sqrt(metrics.mean_absolute_error(density_y_test, y_pred))
new_metrics["R2_test"] = metrics.r2_score(density_y_test, y_pred)

display(old_metrics)
display(new_metrics)
{'RMSE_test': 0.006433043831746894,
 'RMAE_test': 0.07613841884048704,
 'R2_test': 0.989067217447684}
{'RMSE_test': 0.005040505635233745,
 'RMAE_test': 0.06943469212568175,
 'R2_test': 0.9932880934907101}
In [12]:
rules = tree.export_text(
    model,
    feature_names=density_train.columns.values.tolist()
)
print(rules)
|--- Al2O3 <= 0.18
|   |--- TiO2 <= 0.18
|   |   |--- T <= 32.50
|   |   |   |--- TiO2 <= 0.03
|   |   |   |   |--- Al2O3 <= 0.03
|   |   |   |   |   |--- T <= 22.50
|   |   |   |   |   |   |--- value: [1.06]
|   |   |   |   |   |--- T >  22.50
|   |   |   |   |   |   |--- value: [1.06]
|   |   |   |   |--- Al2O3 >  0.03
|   |   |   |   |   |--- value: [1.09]
|   |   |   |--- TiO2 >  0.03
|   |   |   |   |--- T <= 27.50
|   |   |   |   |   |--- T <= 22.50
|   |   |   |   |   |   |--- value: [1.09]
|   |   |   |   |   |--- T >  22.50
|   |   |   |   |   |   |--- value: [1.09]
|   |   |   |   |--- T >  27.50
|   |   |   |   |   |--- value: [1.08]
|   |   |--- T >  32.50
|   |   |   |--- TiO2 <= 0.03
|   |   |   |   |--- Al2O3 <= 0.03
|   |   |   |   |   |--- T <= 55.00
|   |   |   |   |   |   |--- T <= 47.50
|   |   |   |   |   |   |   |--- value: [1.05]
|   |   |   |   |   |   |--- T >  47.50
|   |   |   |   |   |   |   |--- value: [1.04]
|   |   |   |   |   |--- T >  55.00
|   |   |   |   |   |   |--- T <= 62.50
|   |   |   |   |   |   |   |--- value: [1.04]
|   |   |   |   |   |   |--- T >  62.50
|   |   |   |   |   |   |   |--- value: [1.03]
|   |   |   |   |--- Al2O3 >  0.03
|   |   |   |   |   |--- T <= 60.00
|   |   |   |   |   |   |--- T <= 52.50
|   |   |   |   |   |   |   |--- value: [1.07]
|   |   |   |   |   |   |--- T >  52.50
|   |   |   |   |   |   |   |--- value: [1.06]
|   |   |   |   |   |--- T >  60.00
|   |   |   |   |   |   |--- T <= 67.50
|   |   |   |   |   |   |   |--- value: [1.06]
|   |   |   |   |   |   |--- T >  67.50
|   |   |   |   |   |   |   |--- value: [1.05]
|   |   |   |--- TiO2 >  0.03
|   |   |   |   |--- T <= 50.00
|   |   |   |   |   |--- T <= 37.50
|   |   |   |   |   |   |--- value: [1.08]
|   |   |   |   |   |--- T >  37.50
|   |   |   |   |   |   |--- value: [1.08]
|   |   |   |   |--- T >  50.00
|   |   |   |   |   |--- T <= 67.50
|   |   |   |   |   |   |--- T <= 62.50
|   |   |   |   |   |   |   |--- value: [1.06]
|   |   |   |   |   |   |--- T >  62.50
|   |   |   |   |   |   |   |--- value: [1.06]
|   |   |   |   |   |--- T >  67.50
|   |   |   |   |   |   |--- value: [1.06]
|   |--- TiO2 >  0.18
|   |   |--- T <= 40.00
|   |   |   |--- T <= 30.00
|   |   |   |   |--- value: [1.22]
|   |   |   |--- T >  30.00
|   |   |   |   |--- value: [1.21]
|   |   |--- T >  40.00
|   |   |   |--- T <= 60.00
|   |   |   |   |--- T <= 52.50
|   |   |   |   |   |--- T <= 47.50
|   |   |   |   |   |   |--- value: [1.20]
|   |   |   |   |   |--- T >  47.50
|   |   |   |   |   |   |--- value: [1.19]
|   |   |   |   |--- T >  52.50
|   |   |   |   |   |--- value: [1.19]
|   |   |   |--- T >  60.00
|   |   |   |   |--- value: [1.18]
|--- Al2O3 >  0.18
|   |--- T <= 35.00
|   |   |--- T <= 22.50
|   |   |   |--- value: [1.19]
|   |   |--- T >  22.50
|   |   |   |--- T <= 27.50
|   |   |   |   |--- value: [1.18]
|   |   |   |--- T >  27.50
|   |   |   |   |--- value: [1.18]
|   |--- T >  35.00
|   |   |--- T <= 52.50
|   |   |   |--- T <= 42.50
|   |   |   |   |--- value: [1.17]
|   |   |   |--- T >  42.50
|   |   |   |   |--- T <= 47.50
|   |   |   |   |   |--- value: [1.17]
|   |   |   |   |--- T >  47.50
|   |   |   |   |   |--- value: [1.16]
|   |   |--- T >  52.50
|   |   |   |--- T <= 65.00
|   |   |   |   |--- T <= 57.50
|   |   |   |   |   |--- value: [1.16]
|   |   |   |   |--- T >  57.50
|   |   |   |   |   |--- value: [1.15]
|   |   |   |--- T >  65.00
|   |   |   |   |--- value: [1.14]

In [13]:
import pickle

pickle.dump(model, open("data/dtree.model.sav", "wb"))