eogreen's picture
Upload 3 files
9906f45 verified
from warnings import filterwarnings
filterwarnings('ignore')
import pandas as pd
import joblib
from sklearn.datasets import fetch_openml
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import make_column_transformer
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
# Read data
data_df = pd.read_csv('insurance.csv')
data_df = data_df.drop(columns='index')
target = 'charges'
numeric_features = ['age', 'bmi', 'children']
categorical_features = ['sex', 'smoker', 'region']
print("Creating data subsets...")
# Split the data into features and target
X = data_df.drop(target, axis=1)
y = data_df[target]
print('Splitting data into train and test...')
# Split the independent and dependent features into x and y variables with a test size 0.2% and random at 42
Xtrain, Xtest, ytrain, ytest = train_test_split(
X, y,
test_size=0.2,
random_state=42
)
print("Creating model pipeline...")
# Features to scale and encode
preprocessor = make_column_transformer(
(StandardScaler(), numeric_features),
(OneHotEncoder(handle_unknown='ignore'), 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('Model evaluation:')
# print RMSE
print(f" RMSE: {mean_squared_error(ytest, model_pipeline.predict(Xtest), squared=False)}")
# print R2 score
print(f" R2: {r2_score(ytest, model_pipeline.predict(Xtest))}")
# Serialize the model
print("Serializing Model...")
saved_model_path = "model.joblib"
joblib.dump(model_pipeline, saved_model_path)
print('done!')