|
|
|
import math |
|
import pandas as pd |
|
import numpy as np |
|
|
|
from datasets import load_dataset |
|
import sklearn |
|
import joblib |
|
|
|
from sklearn.datasets import fetch_openml |
|
|
|
from sklearn.preprocessing import StandardScaler, OneHotEncoder, LabelEncoder |
|
from sklearn.compose import make_column_transformer |
|
from sklearn.impute import SimpleImputer |
|
from sklearn.pipeline import Pipeline |
|
from sklearn.linear_model import LinearRegression |
|
from sklearn.metrics import mean_squared_error, r2_score |
|
from sklearn.pipeline import make_pipeline |
|
from sklearn.model_selection import train_test_split, RandomizedSearchCV |
|
from sklearn.linear_model import LinearRegression |
|
|
|
data_df = pd.read_csv('insurance.csv') |
|
|
|
data_df = data_df.drop(columns=['index']) |
|
categorical_features = ['sex', 'smoker', 'region'] |
|
numerical_features = ['age', 'bmi', 'children', ] |
|
target = 'charges' |
|
|
|
print("Creating data subsets") |
|
|
|
X = data_df[numerical_features + categorical_features] |
|
y = data_df[target] |
|
|
|
Xtrain, Xtest, ytrain, ytest = train_test_split( X, y, test_size=0.2, random_state=42) |
|
|
|
numerical_pipeline = Pipeline([('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())]) |
|
categorical_pipeline = Pipeline([('imputer', SimpleImputer(strategy='most_frequent')),('onehot', OneHotEncoder(handle_unknown='ignore'))]) |
|
|
|
preprocessor = make_column_transformer((numerical_pipeline, numerical_features), (categorical_pipeline, categorical_features)) |
|
model_linear_regression = LinearRegression(n_jobs=-1) |
|
model_pipeline = make_pipeline(preprocessor, model_linear_regression ) |
|
|
|
print("Estimating Model Pipeline") |
|
model_pipeline.fit(Xtrain, ytrain) |
|
|
|
print("Logging Metrics") |
|
print(f"R-squared: {r2_score(ytest, model_pipeline.predict(Xtest))}") |
|
|
|
print("Serializing Model") |
|
|
|
saved_model_path = "model.joblib" |
|
|
|
joblib.dump(model_pipeline, saved_model_path) |
|
|