<jupyter_start><jupyter_text>**Importing necessary Modules and Libraries**<jupyter_code>import numpy as np
import pandas as pd
import matplotlib.pyplot as pt<jupyter_output><empty_output><jupyter_text>**Reading the data**<jupyter_code>data=pd.read_csv("healthcare-dataset-stroke-data.csv")
data.head(10)
data.info()<jupyter_output><class 'pandas.core.frame.DataFrame'>
RangeIndex: 5110 entries, 0 to 5109
Data columns (total 12 columns):
 #   Column             Non-Null Count  Dtype  
---  ------             --------------  -----  
 0   id                 5110 non-null   int64  
 1   gender             5110 non-null   object 
 2   age                5110 non-null   float64
 3   hypertension       5110 non-null   int64  
 4   heart_disease      5110 non-null   int64  
 5   ever_married       5110 non-null   object 
 6   work_type          5110 non-null   object 
 7   Residence_type     5110 non-null   object 
 8   avg_glucose_level  5110 non-null   float64
 9   bmi                4909 non-null   float64
 10  smoking_status     5110 non-null   object 
 11  stroke             5110 non-null   int64  
dtypes: float64(3), int64(4), object(5)
memory usage: 479.2+ KB<jupyter_text>**Data Analysing**<jupyter_code>new_data=data.drop(columns=['id'])
new_data.head(6)
def bar_plot(variable):

    var = new_data[variable]
    varValue = var.value_counts()
    
    pt.figure(figsize = (9,3))
    pt.bar(varValue.index, varValue)
    pt.xticks(varValue.index, varValue.index.values)
    pt.ylabel("Frequency")
    pt.title(variable)
    pt.show()
    print("{}:\n{}".format(variable,varValue))
categorical = (new_data.dtypes == "object")
categorical_list = list(categorical[categorical].index)

print("Categorical variables:")
print(categorical_list)
categorical_variables = ['gender', 'ever_married', 'work_type', 'Residence_type', 'smoking_status']
for c in categorical_variables:
    bar_plot(c)
def plot_hist(variable):
    pt.figure(figsize = (9,3))
    pt.hist(new_data[variable], bins = 50)
    pt.xlabel(variable)
    pt.ylabel("Frequency")
    pt.title("{} Distribution with Histogram".format(variable))
    pt.show()

numerical_values = (new_data.dtypes == "float64")
numerical_values_list = list(numerical_values[numerical_values].index)

print("Numerical variables:")
print(numerical_values_list)


numerical_variables = ['age', 'avg_glucose_level', 'bmi']
for n in numerical_variables:
    plot_hist(n)<jupyter_output><empty_output><jupyter_text>**Checking for NULL Values**<jupyter_code>new_data[new_data['gender'].isnull()]
new_data[new_data['age'].isnull()]
new_data[new_data['hypertension'].isnull()]
new_data[new_data['heart_disease'].isnull()]
new_data[new_data['ever_married'].isnull()]
new_data[new_data['work_type'].isnull()]
new_data[new_data['Residence_type'].isnull()]
new_data[new_data['avg_glucose_level'].isnull()]
new_data[new_data['bmi'].isnull()]
new_data[new_data['smoking_status'].isnull()]
new_data[new_data['stroke'].isnull()]<jupyter_output><empty_output><jupyter_text>**Removing the NULL Values**<jupyter_code>print("Mean of BMI value for Females: ", np.mean(new_data[new_data['gender'] == 'Female']['bmi']))
print("Mean of BMI value for Males: ", np.mean(new_data[new_data['gender'] == 'Male']['bmi']))
print("Mean of BMI value: ", np.mean(new_data['bmi']))
new_data['bmi'] = new_data['bmi'].fillna(0)
for i in range(0,5035):
    if(new_data['bmi'][i] == 0):
        if(new_data['gender'][i] == 'Male'):
            new_data['bmi'][i] = 28.647936350074616
        elif(new_data['gender'][i] == 'Female'):
            new_data['bmi'][i] = 29.065757680359038
        else:
            new_data['bmi'][i] = 28.893236911794673
        
new_data[new_data['bmi'].isnull()]<jupyter_output><empty_output><jupyter_text>**Converting Categorical variables into Dummy variables**<jupyter_code>print("Unique Values for Gender", new_data['gender'].unique())
print("Unique Values for ever_married", new_data['ever_married'].unique())
print("Unique Values for work_type", new_data['work_type'].unique())
print("Unique Values for Residence_type", new_data['Residence_type'].unique())
print("Unique Values for smoking_status", new_data['smoking_status'].unique())
ever_married_mapping = {'No': 0, 'Yes': 1}
new_data['ever_married'] = new_data['ever_married'].map(ever_married_mapping)
new_data.head()
Residence_type_mapping = {'Rural': 0, 'Urban': 1}
new_data['Residence_type'] = new_data['Residence_type'].map(Residence_type_mapping)
new_data.head()
new_data['gender'] = pd.Categorical(new_data['gender'])
datasetDummies_gender = pd.get_dummies(new_data['gender'], prefix = 'gender_encoded')
datasetDummies_gender
new_data['work_type'] = pd.Categorical(new_data['work_type'])
datasetDummies_work_type = pd.get_dummies(new_data['work_type'], prefix = 'work_type_encoded')
datasetDummies_work_type
new_data['smoking_status'] = pd.Categorical(new_data['smoking_status'])
datasetDummies_smoking_status = pd.get_dummies(new_data['smoking_status'], prefix = 'smoking_status_encoded')
datasetDummies_smoking_status
new_data.drop("gender", axis=1, inplace=True)
new_data.drop("work_type", axis=1, inplace=True)
new_data.drop("smoking_status", axis=1, inplace=True)
new_data = pd.concat([new_data, datasetDummies_gender], axis=1)
new_data = pd.concat([new_data, datasetDummies_work_type], axis=1)
new_data = pd.concat([new_data, datasetDummies_smoking_status], axis=1)
new_data
new_data.info()
stroke_data=new_data["stroke"].copy()
print(stroke_data)
new_data.drop("stroke", axis=1, inplace=True)
new_data = pd.concat([new_data, stroke_data], axis=1)
new_data<jupyter_output><empty_output><jupyter_text>**Separating the Independent and Dependent Features**<jupyter_code>X= new_data.iloc[:,:-1].values
y=new_data.iloc[:,-1].values
X
y<jupyter_output><empty_output><jupyter_text>**Creating the Training and Testing Dataset**<jupyter_code>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=0) 
print(f'Total # of sample in whole dataset: {len(X)}')
print(f'Total # of sample in train dataset: {len(X_train)}')
print(f'Total # of sample in test dataset: {len(X_test)}')
X_train<jupyter_output><empty_output><jupyter_text>**Scaling the Dataset**<jupyter_code>from sklearn.preprocessing import StandardScaler
sc= StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
X_train
len(X_train[0])<jupyter_output><empty_output><jupyter_text>**Creating the Model**<jupyter_code>import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Activation,Dense
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.metrics import categorical_crossentropy

model=Sequential()
model.add(Dense(50,activation='relu',input_shape=(19,)))
model.add(Dense(50,activation='relu'))
model.add(Dense(1,activation='sigmoid'))
model.summary()<jupyter_output>Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense (Dense)                (None, 50)                1000      
_________________________________________________________________
dense_1 (Dense)              (None, 50)                2550      
_________________________________________________________________
dense_2 (Dense)              (None, 1)                 51        
=================================================================
Total params: 3,601
Trainable params: 3,601
Non-trainable params: 0
_________________________________________________________________<jupyter_text>**Training the Model**<jupyter_code>model.compile(optimizer = 'adam',loss = 'binary_crossentropy',metrics = ['accuracy'])
model.fit(X_train,y_train,epochs = 30,batch_size =3)<jupyter_output>Epoch 1/30
1363/1363 [==============================] - 6s 2ms/step - loss: 0.2351 - accuracy: 0.9351
Epoch 2/30
1363/1363 [==============================] - 3s 2ms/step - loss: 0.1474 - accuracy: 0.9553
Epoch 3/30
1363/1363 [==============================] - 3s 2ms/step - loss: 0.1728 - accuracy: 0.9441
Epoch 4/30
1363/1363 [==============================] - 3s 2ms/step - loss: 0.1527 - accuracy: 0.9490
Epoch 5/30
1363/1363 [==============================] - 3s 2ms/step - loss: 0.1453 - accuracy: 0.9509
Epoch 6/30
1363/1363 [==============================] - 3s 2ms/step - loss: 0.1300 - accuracy: 0.9581
Epoch 7/30
1363/1363 [==============================] - 3s 2ms/step - loss: 0.1422 - accuracy: 0.9517
Epoch 8/30
1363/1363 [==============================] - 3s 2ms/step - loss: 0.1184 - accuracy: 0.9619
Epoch 9/30
1363/1363 [==============================] - 3s 2ms/step - loss: 0.1390 - accuracy: 0.9524
Epoch 10/30
1363/1363 [==============================] - 3s 2ms/step - loss: 0.124[...]<jupyter_text>**Testing the Model**<jupyter_code>model.evaluate(x = X_test,y = y_test)
y_test<jupyter_output><empty_output><jupyter_text>**Prediction Analysis**<jupyter_code>y_predict=model.predict(X_test)
y_predict
for i in range(0,len(y_test)-1):
  print("error = "+ str(y_test[i]-y_predict[i]))<jupyter_output>error = [0.07101423]
error = [-5.631007e-27]
error = [-0.012777]
error = [-8.079724e-07]
error = [-5.087104e-23]
error = [-0.00053554]
error = [-3.1334046e-08]
error = [-0.00038733]
error = [-0.01351251]
error = [-0.30108917]
error = [-0.18827368]
error = [-5.1627756e-25]
error = [-8.433131e-22]
error = [-0.5762822]
error = [-1.8421483e-07]
error = [-0.00082812]
error = [-2.860037e-07]
error = [-2.0847425e-05]
error = [-0.00186515]
error = [-0.01936987]
error = [-7.597837e-09]
error = [-7.361503e-25]
error = [-2.4799414e-20]
error = [-3.3833785e-05]
error = [0.96658695]
error = [-0.01600157]
error = [-2.3404734e-15]
error = [-0.01663196]
error = [-1.5882325e-26]
error = [-0.03918773]
error = [-0.00089679]
error = [-0.0004453]
error = [0.96389055]
error = [-2.6928196e-23]
error = [-0.03008372]
error = [-0.01552479]
error = [-0.00886091]
error = [-0.1614559]
error = [-0.01002689]
error = [-5.0276474e-11]
error = [-0.07622115]
error = [-8.186038e-08]
error = [-0.00434748]
error = [-1.1861[...]
{'fraction_non_alphanumeric': 0.18790369935408102, 'fraction_numerical': 0.08269720101781171, 'mean_word_length': 5.23489932885906, 'pattern_counts': {'":': 0, '<': 50, '<?xml version=': 0, '>': 50, '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': '13', 'dir': 'jupyter-structured-clean-dedup', 'id': '448442', 'license': 'MIT', 'n_tokens_mistral': 4178, 'n_tokens_neox': 3620, 'n_words': 643, 'path': 'ML_Project.ipynb', 'repo_name': 'saurav7599/Stroke-Prediction-using-ANN', 'size': '10218'}