In [1]:
#importing libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import average_precision_score
from sklearn.model_selection import cross_val_score
from sklearn.metrics import classification_report,precision_recall_curve,confusion_matrix,accuracy_score,roc_curve,f1_score,auc
Read Data¶
In [2]:
#readdata
df = pd.read_csv("https://cainvas-static.s3.amazonaws.com/media/user_data/cainvas-admin/heart_UC0K8Og.csv")
df.head()
Out[2]:
In [3]:
#plot heatmap
plt.figure(figsize=(14,10))
sns.heatmap(df.corr(),annot=True,fmt='.3f',linewidths=2)
plt.show()
In [ ]:
#plot histogram
df.hist(figsize = (10,10))
Out[ ]:
Data Preprocessing¶
In [ ]:
#data preprocessing
a = pd.get_dummies(df['cp'], prefix = "cp")
b = pd.get_dummies(df['thal'], prefix = "thal")
c = pd.get_dummies(df['slope'], prefix = "slope")
frames = [df, a, b, c]
df = pd.concat(frames, axis = 1)
df = df.drop(columns = ['cp', 'thal', 'slope'])
df.head()
In [ ]:
#printing updated column list
df.columns
In [ ]:
#changing column type to numeric
df = df.apply(pd.to_numeric)
df.dtypes
In [ ]:
#dropping target column
x = df.drop(['target'], axis = 1)
y = df.target.values
Train-Test Split¶
In [ ]:
#train test split
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.3,stratify=y, random_state = 42)
In [ ]:
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
x_train = sc.fit_transform(x_train)
x_test = sc.transform(x_test)
In [ ]:
# convert the data to categorical labels
from tensorflow.keras.utils import to_categorical
y_train = to_categorical(y_train, num_classes=None)
y_test = to_categorical(y_test, num_classes=None)
print (y_train.shape)
In [ ]:
#printing the shape of train data
x_train.shape
Model Architecture¶
In [ ]:
#import library for model making
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras.layers import Activation, Dropout, Flatten, Dense
from tensorflow.keras import regularizers
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import warnings
In [ ]:
#classifier model making
classifier = Sequential()
# add input layer and hidden layer
classifier.add(Dense(
activation="relu", input_dim=21, units=12,
kernel_initializer="normal",kernel_regularizer=regularizers.l2(0.001)
))
classifier.add(Dropout(0.2))
# Adding the output layer
classifier.add(Dense(activation="softmax", units=2))
classifier.save_weights("weights")
In [ ]:
#printing parameters
classifier.summary()
Training the model¶
In [ ]:
#training the model
from tensorflow.keras.optimizers import Adam
classifier.load_weights("weights")
opt3 = Adam(lr=0.001)
classifier.compile(optimizer = opt3, loss = 'categorical_crossentropy', metrics = ['accuracy'])
history = classifier.fit(x_train, y_train,validation_data=(x_test, y_test), batch_size = 10, epochs = 50)
VS Graphs¶
In [ ]:
import matplotlib.pyplot as plt
%matplotlib inline
# Model accuracy
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model Accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'])
plt.show()
In [ ]:
# Model Losss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model Loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'])
plt.show()
Result and Conclusion¶
In [ ]:
#result and conclusion
adam_y_pred = classifier.predict(x_test)
adam_cr = classification_report(y_test,adam_y_pred.round())
print(adam_cr)
Saving the model¶
In [ ]:
#saving the model
classifier.save('heart_disease_ucl.h5')
In [ ]:
from tensorflow.keras.models import load_model
In [ ]:
m = load_model('heart_disease_ucl.h5')
m.predict_classes(x_test)
DeepCC¶
In [ ]:
#deepcc
!deepCC heart_disease_ucl.h5
In [ ]: