File size: 2,101 Bytes
b48fd8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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)