|
import pandas as pd |
|
import joblib |
|
from sklearn.preprocessing import StandardScaler, OneHotEncoder |
|
from sklearn.compose import ColumnTransformer |
|
from sklearn.model_selection import train_test_split, RandomizedSearchCV |
|
from sklearn.linear_model import Ridge |
|
from sklearn.pipeline import Pipeline |
|
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score |
|
|
|
|
|
df = pd.read_csv('/insurance (1).csv') |
|
|
|
|
|
y = df['charges'] |
|
|
|
|
|
numerical_columns = ['age', 'bmi', 'children'] |
|
categorical_columns = ['sex', 'smoker', 'region'] |
|
|
|
|
|
X = df[numerical_columns + categorical_columns] |
|
|
|
|
|
Xtrain, Xtest, ytrain, ytest = train_test_split( |
|
X, y, |
|
test_size=0.2, |
|
random_state=42 |
|
) |
|
|
|
|
|
preprocessor = ColumnTransformer( |
|
transformers=[ |
|
('num', StandardScaler(), numerical_columns), |
|
('cat', OneHotEncoder(handle_unknown='ignore'), categorical_columns) |
|
] |
|
) |
|
|
|
|
|
ridge_pipeline = Pipeline([ |
|
('preprocessor', preprocessor), |
|
('ridge', Ridge()) |
|
]) |
|
|
|
|
|
param_distribution = { |
|
'ridge__alpha': [0.001, 0.01, 0.1, 0.5, 1, 5, 10] |
|
} |
|
|
|
|
|
random_search = RandomizedSearchCV(ridge_pipeline, param_distribution, n_iter=5, cv=5) |
|
random_search.fit(Xtrain, ytrain) |
|
|
|
|
|
y_pred = random_search.best_estimator_.predict(Xtest) |
|
|
|
mae = mean_absolute_error(ytest, y_pred) |
|
mse = mean_squared_error(ytest, y_pred) |
|
r2 = r2_score(ytest, y_pred) |
|
|
|
print("The model performance for the testing set") |
|
print("--------------------------------------") |
|
print('MAE is {}'.format(mae)) |
|
print('MSE is {}'.format(mse)) |
|
print('R2 score is {}'.format(r2)) |
|
|
|
|
|
saved_model_path = "model.joblib" |
|
joblib.dump(random_search.best_estimator_, saved_model_path) |
|
|