"""
<center><img src ='https://medicineforthemindblog.files.wordpress.com/2017/08/brain-pic.jpg' width = '600px'></center>
<center><img src='https://i.imgur.com/SZQXq1q.png' width = '600px'></center>
"""
"""
<p style='font-size:17px;font-weight:bold'>A <span style='color:#f54025'>stroke</span> occurs when the blood supply to part of your brain is interrupted or reduced, preventing brain tissue from getting oxygen and nutrients. Brain cells begin to die in minutes. <span style='color:#f54025'>Stroke</span> has already reached epidemic proportions. Globally 1 in 4 adults over the age of 25 will have a <span style='color:#f54025'>stroke</span> in their lifetime. 13.7 million people worldwide will have their first <span style='color:#f54025'>stroke</span> this year and five and a half million will die as a result.</p>
"""
"""
<p style = 'font-size : 17px;font-style: italic'>
    <span style ='font-size:19px;font-weight:bold;color:#9ACD32'>Attribute Information<br></span>
1) id:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; unique identifier<br>
2) gender:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;"Male", "Female" or "Other"<br>
3) age:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; age of the patient<br>
4) hypertension:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; 0 if the patient doesn't have hypertension, 1 if the patient has hypertension<br>
5) heart_disease:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;0 if the patient doesn't have any heart diseases, 1 if the patient has a heart disease<br>
6) ever_married:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;"No" or "Yes"<br>
7) work_type:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; "children", "Govt_jov", "Never_worked", "Private" or "Self-employed"<br>
8) Residence_type:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;"Rural" or "Urban"<br>
9) avg_glucose_level:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; average glucose level in blood<br>
10) bmi:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; body mass index<br>
11) smoking_status:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; "formerly smoked", "never smoked", "smokes" or "Unknown"*<br>
12) stroke:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; 1 if the patient had a stroke or 0 if not<br>
*Note: "Unknown" in smoking_status means that the information is unavailable for this patient
</p>
"""
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from catboost import CatBoostClassifier
from lightgbm import LGBMClassifier
from xgboost import XGBClassifier
from sklearn.metrics import accuracy_score
import warnings
warnings.filterwarnings('ignore')
"""
<h1 id="heading1">
<span style="font-size:30px;color:#9ACD32;font-weight:bold"><center>Exploring Data</center></span>
      <a class="anchor-link" href="https://www.kaggle.com/alampalsingh/notebook004d896e8c#heading1" target ="_self"></a>
</h1>
"""
df = pd.read_csv('../input/stroke-prediction-dataset/healthcare-dataset-stroke-data.csv')
df
df.info()
df.stroke
df.drop(['id'],axis=1,inplace=True)
"""
<center><span style = 'font-size:19px;font-weight:bold'>Dividing Data into Categorical and Integer/Float Data</span>
"""
cat = []
inf = []
for i in range(0,df.shape[1]):
    if df.iloc[:,i].dtype == object:
        cat.append(df.iloc[:,i].name)
    else:
        inf.append(df.iloc[:,i].name)

cat
inf
"""
<center><span style = 'font-size:19px;font-weight:bold'>Categorical Data</span>
"""
fig=plt.figure(figsize=(20,10),facecolor = '#fbe7dd')
columns = 3
rows = 2
a=np.random.rand(2,3)
for i in range(1,len(cat)+1):
    fig.add_subplot(rows, columns, i)
    sns.countplot(df[cat[i-1]],palette='Spectral_r') 
plt.show()
    
plt.figure(figsize=(10,6),facecolor = '#fbe7dd')
plt.pie(df.stroke.value_counts(),labels=['Stroke','No Stroke'],startangle=40,explode=[0,0.15],shadow=True,colors=['#FFA177FF','#F5C7B8FF'],autopct = '%1.1f%%')
plt.axis('equal')
plt.show()
_,ax = plt.subplots(1,2,figsize=(20,8),facecolor='#fbe7dd')
sns.countplot(df.gender,hue =  df.stroke,palette='Spectral_r',ax =ax[0])
sns.countplot(df.smoking_status,hue = df.stroke,ax=ax[1],palette='Spectral_r')
plt.show()
gs0 = df[df.stroke == 0].gender.value_counts()
gs1 = df[df.stroke == 1].gender.value_counts()
ss0 = df[df.stroke == 0].smoking_status.value_counts()
ss1 = df[df.stroke == 1].smoking_status.value_counts()
gs1
_,ax= plt.subplots(2,2,figsize=(20,12),facecolor='#fbe7dd')
ax[0][0].pie(gs0,labels=['Female','Male','Other'],shadow =True,autopct = '%1.1f%%',explode = [0.03,0.03,0.03],colors =['#dee9a4','#72b7a1','#de7959'])
ax[0][1].pie(gs1,labels=['Female','Male'],shadow =True,autopct = '%1.1f%%',explode = [0.03,0.03],colors =['#dee9a4','#72b7a1'])
ax[1][0].pie(ss0,labels=['Never Smoked','Formerly Smoked','Unknown','Smokes'],shadow =True,autopct = '%1.1f%%',explode = [0.04,0.04,0.04,0.04],colors =['#dee9a4','#72b7a1','#de7959','#f0d999'])
ax[1][1].pie(ss1,labels=['Never Smoked','Formerly Smoked','Unknown','Smokes'],shadow =True,autopct = '%1.1f%%',explode = [0.04,0.04,0.04,0.04],colors =['#dee9a4','#72b7a1','#de7959','#f0d999'])
ax[0][0].set_title('Stroke = 0',fontsize= 30)
ax[0][1].set_title('Stroke = 1',fontsize= 30)
plt.show()
#f, ax = plt.subplots(figsize=(10, 8))
#ax.set_aspect("equal")

# Draw a contour plot to represent each bivariate density
#sns.kdeplot(
    #data=df,
    #y="gender",
    #x="heart_disease",
    #hue="stroke",
    ##thresh=.1,
#)
"""
<center><span style = 'font-size:19px;font-weight:bold'>Integer/Float Data</span></center>
"""
fig=plt.figure(figsize=(20,10),facecolor='#fbe7dd')
columns = 3
rows = 2
a=np.random.rand(2,3)
for i in range(1,len(inf)):
    fig.add_subplot(rows, columns, i)
    sns.kdeplot(df[inf[i-1]],hue = df.stroke) 
plt.show()

df.gender[df.gender == 'Other']
df.bmi.fillna(df.bmi.mean(),inplace=True)
df = pd.get_dummies(df)
x= df.drop(['stroke','gender_Other'],axis = 1)
nu = ['age','bmi','avg_glucose_level']
sc = StandardScaler()
x[nu] = sc.fit_transform(x[nu])
y = df.stroke
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=44)
"""
<h1 id="heading2">
<span style="font-size:30px;color:#9ACD32;font-weight:bold"><center>Model Fitting</center></span>
<a class="anchor-link" href="https://www.kaggle.com/alampalsingh/notebook004d896e8c#heading2" target ='_self'></a>
</h1>
"""
score ={}
rfc = RandomForestClassifier()
rfc.fit(x_train,y_train)
score['Random Forest'] = accuracy_score(y_test,rfc.predict(x_test))
accuracy_score(y_test,rfc.predict(x_test))
lgb = LGBMClassifier(learning_rate = 0.1,reg_alpha = 0.3,n_estimators = 100).fit(x_train,y_train)
score['LightGBM'] = (accuracy_score(y_test,lgb.predict(x_test)))
(accuracy_score(y_test,lgb.predict(x_test)))
xgb = XGBClassifier().fit(x_train,y_train)
score['XGBoost'] =accuracy_score(y_test,xgb.predict(x_test))
accuracy_score(y_test,xgb.predict(x_test))
cbc = CatBoostClassifier(n_estimators=150,l2_leaf_reg=0.1,verbose = 0).fit(x_train,y_train)
score['Cat Boost'] = accuracy_score(y_test,cbc.predict(x_test))
accuracy_score(y_test,cbc.predict(x_test))
key = list(score.keys())
val = list(float(score[k]) for k in key)
plt.figure(figsize = (16,6))
score = sns.barplot(val,key,palette="Spectral_r")
for i in range(0,len(key)):
    score.text(val[i]/2,i,str(np.round(val[i],4)),fontdict = dict(fontsize = 12,ha = 'center',va = 'center'),weight = 'bold')
"""
<center><span style="font-size:25px;color:#9ACD32;font-weight:bold">If you find this notebook helpful, don't forget to </span><span style= 'font-size:25px;color:#b7410e;font-weight:bold'>upvote.
"""