Welfab's picture
Upload 4 files
b48fd8e verified
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
# Read the uploaded file
df = pd.read_csv('/insurance (1).csv')
# Define the target variable
y = df['charges']
# Define the feature columns
numerical_columns = ['age', 'bmi', 'children']
categorical_columns = ['sex', 'smoker', 'region']
# Define feature matrix X
X = df[numerical_columns + categorical_columns]
# Split the data
Xtrain, Xtest, ytrain, ytest = train_test_split(
X, y,
test_size=0.2,
random_state=42
)
# Create a column transformer for preprocessing
preprocessor = ColumnTransformer(
transformers=[
('num', StandardScaler(), numerical_columns), # Standard scaling for numerical columns
('cat', OneHotEncoder(handle_unknown='ignore'), categorical_columns) # One-hot encoding for categorical columns
]
)
# Create a Ridge regression model pipeline
ridge_pipeline = Pipeline([
('preprocessor', preprocessor),
('ridge', Ridge())
])
# Define a parameter distribution for hyperparameter tuning
param_distribution = {
'ridge__alpha': [0.001, 0.01, 0.1, 0.5, 1, 5, 10]
}
# Perform hyperparameter tuning using RandomizedSearchCV
random_search = RandomizedSearchCV(ridge_pipeline, param_distribution, n_iter=5, cv=5)
random_search.fit(Xtrain, ytrain)
# Model evaluation for testing set
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))
# Save the best model
saved_model_path = "model.joblib"
joblib.dump(random_search.best_estimator_, saved_model_path)