<jupyter_start><jupyter_text>Heart Failure Prediction<jupyter_code>import pandas as pd
import numpy as np
import sklearn
import matplotlib.pyplot as plt
import seaborn as sb
#importing data
data=pd.read_csv('heart_failure_clinical_records_dataset.csv')
data.info()
#checking null values
data.isnull().sum()
data.describe()<jupyter_output><empty_output><jupyter_text>Meaning of Variables:Age - Self ExplanatoryAnaemia - Is 1 or 0 with 1 being the patient does have this condition. Anemia is a condition in which you lack enough healthy red blood cells to carry adequate oxygen to your body's tissues.Creatinine Phosphokinase - Level of CPK enzyme in the bloodDiabetes - Is a 1 or 0 - whether the patient suffers from diabetes or not - similar to anaemiaEjection Fraction - Is a percentage (numerical between 0 to 100) Ejection fraction is a measurement of the percentage of blood leaving your heart each time it contracts.High Blood Pressure - Is a 1 or 0 - whether patient suffers from high blood pressurePlatelets - no. of platelets in the bloodSerum Creatine - Level of Creatine produced from the kidneys in the bloodSerum Sodium - Level of Sodium in the bloodSex - Self Explanatory - assuming 1 is male and 0 is femaleSmoking - Self Explanatory - assuming 1 is smokes and 2 is doesn't smokeTime - Follow up daysDeath Event - whether patient died during follow up period<jupyter_code>sb.set_style('darkgrid')
sb.countplot(x='DEATH_EVENT',data= data)<jupyter_output><empty_output><jupyter_text>out of 299 patients 96 patients died<jupyter_code>#count of diabetic patients 
sb.set_style('darkgrid')
sb.countplot(x='diabetes',data= data)<jupyter_output><empty_output><jupyter_text>125 patients are diabetic<jupyter_code>#To find age of most patients
sb.distplot(data['age'],kde=False,color='darkblue',bins=25)<jupyter_output><empty_output><jupyter_text>majority patients are in the age of 50-70.<jupyter_code>sb.distplot(data['creatinine_phosphokinase'],kde=False,color='green',bins=25)<jupyter_output><empty_output><jupyter_text>most patients creatinine_phosphokinase is below 1000<jupyter_code>sb.distplot(data['serum_creatinine'],kde=False,color='red',bins=25)<jupyter_output><empty_output><jupyter_text>most patients serum_creatinine is below 2<jupyter_code>a = (len(data[data['anaemia'] == 1]))/len(data['anaemia'])
b = (len(data[data['diabetes'] == 1]))/len(data['diabetes'])
c = (len(data[data['high_blood_pressure'] == 1]))/len(data['high_blood_pressure'])
d = (len(data[data['sex'] == 1]))/len(data['sex'])
e = (len(data[data['smoking'] == 1]))/len(data['smoking'])

data1 = {'Anaemia': a, 'Diabetes': b, 'High Blood Pressure': c, 'Sex': d, 
       'Smoking': e}
x1 = pd.DataFrame(data1,index=[1])
x1<jupyter_output><empty_output><jupyter_text>Around 40% of patients  either  have  Anaemia or diabetes or both . Around 65% of the patients were male(consider male==1)  Around a third of patients suffered from either High Blood Pressure, Smoking or both<jupyter_code>#checking the effect of smoke,diabetes,gender,anaemia,high_blood_pressure on death event



data[['sex', 'DEATH_EVENT']].groupby(['sex'],as_index=False).mean()
data[['diabetes','DEATH_EVENT']].groupby(['diabetes'],as_index=False).mean()
data[['anaemia','DEATH_EVENT']].groupby(['anaemia'],as_index=False).mean()
data[['high_blood_pressure','DEATH_EVENT']].groupby(['high_blood_pressure'],as_index=False).mean()
data[['smoking','DEATH_EVENT']].groupby(['smoking'],as_index=False).mean()<jupyter_output><empty_output><jupyter_text>from the above obsevation the effect of smoke,diabetes,gender,anaemia,high_blood_pressure on death_event is low.<jupyter_code>plt.figure(figsize=(12,6))
sb.heatmap(data.corr(),cmap='seismic' , annot = True)<jupyter_output><empty_output><jupyter_text>we drop correlation less than 0.1<jupyter_code>datacor = data.corr() 
data_target = abs(datacor["DEATH_EVENT"])
relevant_features = data_target[data_target>0.1]
relevant_features
#droping coloumns
data.drop('anaemia',axis=1,inplace=True)
data.drop('diabetes',axis=1,inplace=True)
data.drop('high_blood_pressure',axis=1,inplace=True)
data.drop('sex',axis=1,inplace=True)
data.drop('creatinine_phosphokinase',axis=1,inplace=True)
data.drop('platelets',axis=1,inplace=True)
data.drop('smoking',axis=1,inplace=True)
data.info()
#split the data into X & Y
X = data.iloc[:,0:5].values
Y = data.iloc[:,-1].values

print(X)
print(Y)
#split the dataset into 80% train and 20% test

from sklearn.model_selection import train_test_split

X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=.2,random_state=42)<jupyter_output><empty_output><jupyter_text>Logistic Regression<jupyter_code>from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
model.fit(X_train,Y_train)
from sklearn.metrics import accuracy_score

pred = model.predict(X_test)
accuracy=accuracy_score(Y_test,pred)
accuracy
from sklearn.metrics import confusion_matrix
from sklearn.metrics import plot_confusion_matrix

confusion_matrix =  confusion_matrix(Y_test,pred)

confusion_matrix
print(Y_test)
print(pred)
plot_confusion_matrix(model,X_test,Y_test,cmap='PuBuGn')
plt.show()<jupyter_output><empty_output><jupyter_text>KNN classifier<jupyter_code>from sklearn.neighbors import KNeighborsClassifier
knn=KNeighborsClassifier(n_neighbors=1)
knn.fit(X_train,Y_train)


from sklearn.metrics import accuracy_score

pred = knn.predict(X_test)
accuracy=accuracy_score(Y_test,pred)
accuracy
from sklearn.metrics import confusion_matrix
from sklearn.metrics import plot_confusion_matrix

confusion_matrix =  confusion_matrix(Y_test,pred)

confusion_matrix
plot_confusion_matrix(knn,X_test,Y_test,cmap='nipy_spectral',)
plt.show()<jupyter_output><empty_output><jupyter_text>XGBoost model<jupyter_code>from xgboost.sklearn import XGBClassifier
model = XGBClassifier(random_state=42)
model.fit(X, Y)
from sklearn.metrics import accuracy_score

pred = model.predict(X_test)
accuracy=accuracy_score(Y_test,pred)
accuracy
from sklearn.metrics import confusion_matrix
from sklearn.metrics import plot_confusion_matrix

confusion_matrix =  confusion_matrix(Y_test,pred)

confusion_matrix
plot_confusion_matrix(model,X_test,Y_test,cmap='jet',)
plt.show()<jupyter_output><empty_output><jupyter_text>GaussianNB<jupyter_code>from sklearn.naive_bayes import GaussianNB
gauss=GaussianNB()
gauss.fit(X_train,Y_train)
pred = gauss.predict(X_test)

from sklearn.metrics import accuracy_score

accuracy=accuracy_score(Y_test,pred)
accuracy
from sklearn.metrics import confusion_matrix
from sklearn.metrics import plot_confusion_matrix

confusion_matrix =  confusion_matrix(Y_test,pred)

confusion_matrix
plot_confusion_matrix(gauss,X_test,Y_test,cmap='Pastel1',)
plt.show()<jupyter_output><empty_output><jupyter_text>DecisionTreeClassifier<jupyter_code>from sklearn.tree import DecisionTreeClassifier
tree=DecisionTreeClassifier()
tree.fit(X_train,Y_train)

pred = tree.predict(X_test)

from sklearn.metrics import accuracy_score

accuracy=accuracy_score(Y_test,pred)
accuracy
from sklearn.metrics import confusion_matrix
from sklearn.metrics import plot_confusion_matrix

confusion_matrix =  confusion_matrix(Y_test,pred)

confusion_matrix
plot_confusion_matrix(tree,X_test,Y_test,cmap='Set2',)
plt.show()<jupyter_output><empty_output><jupyter_text>SVC(kernel='linear')<jupyter_code>from sklearn.svm import SVC
svc=SVC(kernel='linear')
svc.fit(X_train,Y_train)

pred = svc.predict(X_test)

from sklearn.metrics import accuracy_score

accuracy=accuracy_score(Y_test,pred)
accuracy
from sklearn.metrics import confusion_matrix
from sklearn.metrics import plot_confusion_matrix

confusion_matrix =  confusion_matrix(Y_test,pred)

confusion_matrix
plot_confusion_matrix(svc,X_test,Y_test,cmap='Set3',)
plt.show()<jupyter_output><empty_output><jupyter_text>RandomForestClassifier<jupyter_code>from sklearn.ensemble import RandomForestClassifier
forest=RandomForestClassifier(n_estimators=10)
forest.fit(X_train,Y_train)

pred = forest.predict(X_test)

from sklearn.metrics import accuracy_score

accuracy=accuracy_score(Y_test,pred)
accuracy
from sklearn.metrics import confusion_matrix
from sklearn.metrics import plot_confusion_matrix

confusion_matrix =  confusion_matrix(Y_test,pred)

confusion_matrix
plot_confusion_matrix(forest,X_test,Y_test,cmap='Paired',)
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10996274486239635, 'fraction_numerical': 0.010215118375195288, 'mean_word_length': 9.481108312342569, 'pattern_counts': {'":': 0, '<': 69, '<?xml version=': 0, '>': 70, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '17', 'dir': 'jupyter-structured-clean-dedup', 'id': '260865', 'license': 'CC-BY-4.0', 'n_tokens_mistral': 3036, 'n_tokens_neox': 2860, 'n_words': 554, 'path': 'heart failure prediction.ipynb', 'repo_name': 'amaljith6/Heart-Failure-Prediction', 'size': '8321'}