File size: 4,011 Bytes
08e38f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# import the library
import pandas as pd
import numpy as np
import seaborn as sns
from sklearn.preprocessing import OrdinalEncoder, OneHotEncoder
from sklearn.preprocessing import StandardScaler

from sklearn.impute import KNNImputer
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer


from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import GradientBoostingClassifier

#libraries for model evaluation
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
from sklearn.metrics import plot_confusion_matrix
from sklearn.metrics import classification_report

import warnings
warnings.filterwarnings('ignore')

# read the dataset
df = pd.read_csv('heart.csv')

# get categorical columns
categorical_cols= df.select_dtypes(include=['object'])

# get count of unique values for categorical columns
for cols in categorical_cols.columns:
    print(cols,':', len(categorical_cols[cols].unique()),'labels')

# categorical columns
cat_col = categorical_cols.columns

# numerical column
num_col = ['Age','RestingBP','Cholesterol','FastingBS','MaxHR','Oldpeak']

# define X and y
X = df.drop(['HeartDisease'],axis=1)
y = df['HeartDisease']

# create a pipeline for preprocessing the dataset

num_pipeline = Pipeline([
        ('imputer', KNNImputer(n_neighbors=5)),
        ('std_scaler', StandardScaler()),
    ])

num_attribs = num_col 
cat_attribs = cat_col

# apply transformation to the numerical and categorical columns
full_pipeline = ColumnTransformer([
        ("num", num_pipeline, num_attribs),
        ("cat", OneHotEncoder(), cat_attribs),
    ])

X = full_pipeline.fit_transform(X)

# save preprocessed data
temp_df = pd.DataFrame(X)
temp_df.to_csv('processed_data.csv')

# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)

# count plot for number of heart disease(1)/No heart disease(0)
import seaborn as sns
sns.countplot(y_train,palette='OrRd')

# create a fresh model based on tuned parameters
rfc1=RandomForestClassifier(random_state=42, max_features='sqrt', n_estimators= 50, max_depth=7, criterion='gini')

rfc1.fit(X_train, y_train)

# Predicting the Test set results
y_pred = rfc1.predict(X_test)
print('Random forest accuracy_score:',accuracy_score(y_test,y_pred))

# Save the Model

import pickle

# save the random forest model for future use
pickle.dump(rfc1, open('rfc.pickle', 'wb'))

# save the preprocessing pipeline
pickle.dump(full_pipeline, open('full_pipeline.pickle', 'wb'))

# Load the Models for future use

rfc_saved = pickle.load(open('rfc.pickle','rb'))
full_pipeline_saved = pickle.load(open('full_pipeline.pickle','rb'))

# Visualization

target = df['HeartDisease'].replace([0,1],['Low','High'])

data = pd.crosstab(index=df['Sex'],
           columns=target)

data.plot(kind='bar',stacked=True)
plt.show()

plt.figure(figsize=(10,5))
bins=[0,30,50,80]
sns.countplot(x=pd.cut(df.Age,bins=bins),hue=target,color='r')
plt.show()

plt.figure(figsize=(10,5))
sns.countplot(x=target,hue=df.ChestPainType)
plt.xticks(np.arange(2), ['No', 'Yes']) 
plt.show()

plt.figure(figsize=(10,5))
sns.countplot(x=target,hue=df.ExerciseAngina)
plt.xticks(np.arange(2), ['No', 'Yes']) 
plt.show()

# feature importance

# get important features used by model 
importances = rfc1.feature_importances_
feature_names = num_col
for i in cat_col:
    feature_names = feature_names + [i]*df[i].nunique()

import pandas as pd

forest_importances = pd.Series(importances, index=feature_names)

forest_importances = forest_importances.groupby(level=0).first().sort_values(ascending=False)

# plot the features based on their importance in model performance.
fig, ax = plt.subplots()
forest_importances.plot.bar()
ax.set_title("Feature importances using MDI")
ax.set_ylabel("Mean decrease in impurity")
fig.tight_layout()