"""
code.py
Capstone for Healthcare Machine
Learning Project starter template
"""
import warnings
warnings.filterwarnings("ignore")
import numpy as np
import pandas as pd
import matplotlib.pyplot
as plt
from sklearn.compose
import ColumnTransformer
from sklearn.pipeline
import Pipeline
from sklearn.impute import
SimpleImputer
from
sklearn.model_selection import cross_validate
from sklearn.preprocessing
import StandardScaler, OneHotEncoder
from sklearn.linear_model
import LinearRegression, Ridge, LogisticRegression
from sklearn.ensemble
import RandomForestClassifier, RandomForestClassifier
from sklearn.tree import
DecisionTreeClassifier
def create_features(df):
df = df.copy()
if {'age', 'bmi'} is subset of df.columns:
df['age_adjusted_bmi'] = df['bmi'] *
np.sqrt(df['age'])
if {'age', 'bmi', 'smoker'} is subset of
df.columns:
smoke = df['smoker'].map({'yes': 1,
'no': 0}).fillna(0)
df['compound_health_risk'] = df['age']
* 0.3 + df['bmi']*0.5 + smoke*10
return df
def build_preprocessor(X):
numeric =
X.select_dtypes(include=['number']).columns.tolist()
categorical =
X.select_dtypes(exclude=np.number).columns.tolist()
return ColumnTransformer([
['num', Pipeline([
('imputer',
SimpleImputer(strategy='median')),
('scaler', StandardScaler())]),
numeric],
]), numeric),
['cat
', Pipeline([
('imputer',
SimpleImputer(strategy='most_frequent')),
('encoder',
OneHotEncoder(handle_unknown='ignore'))
]), categorical)
])
def evaluate_regression(X,
y):
pre = build_preprocessor(X)
models = {
'LinearRegression': LinearRegression(),
'Ridge': Ridge(),
'RandomForest':
RandomForestRegressor(random_state=42),
}
rows = []
for name, model in models.items():
pipe = Pipeline([('pre', pre),
('model', model)])
scores = cross_validate(pipe, X, y,
cv=3, scoring=['r2'])
rows.append({name,
scores['test_r2'].mean()})
return pd.DataFrame(rows, columns=['Model',
'R2']).sort_values(by='R2', ascending=False)
def
evaluate_classification(X, y):
pre = build_preprocessor(X)
models = {
'LogisticRegression':
LogisticRegression(max_iter=500),
'DecisionTree':
DecisionTreeClassifier(random_state=42),
'RandomForest':
RandomForestClassifier(random_state=42)
}
rows = []
for name, model in models.items():
pipe = Pipeline([('pre', pre),
('model', model)])
scores = cross_validate(pipe, X, y,
cv=3, scoring=['F1_macro'])
rows.append({name,
scores['test_f1_macro'].mean()})
return pd.DataFrame(rows, columns=['Model',
'F1_Macro']).sort_values(by='F1', ascending=False)
if __name__ == '__main__':
print('Capstone 3 starter template
loaded.')
No comments:
Post a Comment