image_output_1.png
from IPython.display import display

import ipywidgets as widgets

import matplotlib.pyplot as plt

import pandas as pd

import seaborn           as sns

import warnings

import numpy as np
import pandas as pd
pd.set_option('display.max_columns', None)
from colorama import Fore, Style
from sklearn.tree import plot_tree
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
from ipywidgets import HBox, Output, VBox, Layout
from IPython.display import display
import ipywidgets as widgets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.feature_selection import f_classif, mutual_info_classif
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier
from xgboost import XGBClassifier, XGBRegressor
from catboost import CatBoostClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import roc_auc_score, accuracy_score, recall_score, precision_score, f1_score, classification_report, plot_confusion_matrix, plot_roc_curve, plot_precision_recall_curve, log_loss, brier_score_loss, hamming_loss
import warnings
warnings.filterwarnings('ignore')

data = pd.read_csv('../input/heart-attack-analysis-prediction-dataset/heart.csv')
data.sort_values('age').head()

data_eda = data.copy()
data_eda['sex'] = data['sex'].map({1: 'Male', 0: 'Female'})
data_eda['cp'] = data['cp'].map({1: 'Typical\nangina', 2: 'Atypical\nangina', 3: 'Non-anginal\npain', 0: 'Asymptomatic'})
data_eda['fbs'] = data['fbs'].map({1: 'True', 0: 'False'})
data_eda['restecg'] = data['restecg'].map({1: 'Normal', 2: 'Having\nST-T wave\nabnormality', 0: 'Hypertrophy'})
data_eda['exng'] = data['exng'].map({1: 'Yes', 0: 'No'})
data_eda['slp'] = data['slp'].map({2: 'Upsloping', 1: 'Flat', 0: 'Downsloping'})
data_eda['caa'] = data['caa'].map({0: '0', 1: '1', 2: '2', 3: '3', 4: '3'})
data_eda['thall'] = data['thall'].map({0: 'Normal', 2: 'Normal', 1: 'Fixed defect', 3: 'Reversible\ndefect'})
data_eda['output'] = data['output'].map({1: 'Yes', 0: 'No'})

data_eda.isnull().mean()

## cohort analysis of age with output
def age_cohort(age):
    if age <= 45:
        return "0-45"
    elif age > 45 and age <= 55:
        return "45-55"
    elif age > 55 and age <= 60:
        return "55-60"
    elif age > 60:
        return "60+"
        
data_eda['age group'] = data_eda['age'].apply(age_cohort)
data_eda.sort_values("age group",inplace=True)

def q(n):
    def q_(x):
        return x.quantile(n)
    q_.__name__ = '{:2.0f}%'.format(n*100)
    return q_

def ctab(var):
    f, a = plt.subplots(1, 2,figsize=(8,3),dpi=200)
    background_color = "#F0F6FC"
    color = "#000000"
    hue_colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
    f.patch.set_facecolor(background_color)
    temp=data_eda[var].value_counts()
    a[1].pie(x=temp,labels=temp.index,autopct='%1.1f%%',textprops={'fontsize':9},colors=hue_colors);
    a[1].set_xlabel(var)
    a[0].axis("off")
    a[0].text(.55,0.5," Percentage( % ) \n", 
                              color   =color,   horizontalalignment = 'center',verticalalignment = 'center'  ,                          
                              fontsize = 20,    fontfamily='serif');

    a[0].text(.55,0.4,"of Categorical Feature '"+var+"'\n_________________________________",
                              color    = color, horizontalalignment = 'center',verticalalignment = 'center'  ,                          
                              fontsize = 10,    fontfamily='serif');
    plt.show()

ci        = ["Categorical Features", "Numeric Features"]
cat_var   = [var for var in data_eda.columns if data_eda[var].dtype=='O' and var !='output']
num_var   = [var for var in data_eda.columns if data_eda[var].dtype!='O']

# Create inner Tabs
def create_inner_tabs():        
    inner_tabs_list=[widgets.Output() for i in range(len(cat_var))]
    inner_tab = widgets.Tab(inner_tabs_list)
    for i in range (len(cat_var)):
        inner_tab.set_title(i,cat_var[i])

        with inner_tabs_list[i]:      
            ctab(cat_var[i]);
    display(inner_tab)
    

# Create outer Tabs
outer_sub_tabs_list=[widgets.Output() for i in range(len(ci))]
tab = widgets.Tab(children=outer_sub_tabs_list)
for i in range (len(ci)):
    tab.set_title(i,ci[i])
                      
    with outer_sub_tabs_list[i]:
        if i ==0:
            create_inner_tabs();
        else:
            plt.figure(figsize=(11,4),dpi=200)
            df_n=data_eda[num_var].agg(["count","mean","std","skew","kurt","min",q(.25),"median",q(.75),"max"]).T
            df_n["range"]=df_n["max"]-df_n["min"]
            df_n["IQR"]  =df_n["75%"]-df_n["25%"]
            sns.heatmap(df_n , annot=True,cmap = "Blues", fmt= '.2f',linewidths = 5, cbar = False,annot_kws={"size": 10})
            plt.xticks(size = 12);
            plt.yticks(size = 12, rotation = 0);
            plt.title("Descriptive Statistics", size = 16)
            plt.show()
            
                   
display(tab)    

f, a = plt.subplots(5, 2, figsize=(12, 15), dpi=200)
background_color = '#F0F6FC'
color = '#000000'
hue_color = ['#FF5003', '#428bca']
hue_order = ['Yes', 'No']
alpha = 0.8
f.patch.set_facecolor(background_color)
ax = sum(a.tolist(), [])[1:]
a[0][0].axis('off')
a[0][0].text(0.5, 0.4, 'Bar Plots (%)\n', color=color, horizontalalignment='center', verticalalignment='center', fontsize=31, fontfamily='serif')
a[0][0].text(0.5, 0.3, 'of Categorical Features\n________________________', color=color, horizontalalignment='center', verticalalignment='center', fontsize=16.9, fontfamily='serif')
for i in range(len(cat_var)):
    new_df = data_eda.groupby(cat_var[i])['output'].value_counts(normalize=True).mul(100).rename('Percent ( % )').reset_index()
    g = sns.barplot(data=new_df, x=cat_var[i], y='Percent ( % )', hue='output', ax=ax[i], palette=hue_color, alpha=alpha, edgecolor=background_color, hue_order=hue_order)
    ax[i].set_facecolor(background_color)
    ax[i].grid(color=background_color)
    ax[i].grid(color=color, linestyle=':', axis='y', zorder=0, dashes=(1, 5))
    ax[i].spines['top'].set_visible(False)
    ax[i].spines['right'].set_visible(False)
    ax[i].spines['left'].set_visible(False)
    ax[i].spines['bottom'].set_color(color)
    ax[i].xaxis.label.set_color(color)
    ax[i].yaxis.label.set_color(color)
    ax[i].tick_params(axis='x', colors=color)
    ax[i].tick_params(axis='y', colors=color)
    if i == 1:
        l = ax[i].legend(loc=(0.4, 1.1), facecolor=background_color, edgecolor=background_color, title='Heart Attack', fontsize=10, title_fontsize=14)
        for text in l.get_texts():
            text.set_color(color)
        l._legend_title_box._text.set_color(color)
    else:
        ax[i].legend().set_visible(False)
    plt.tight_layout()