# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/suyash091/Cardiovascular-Disease-Prediction/blob/master/Cardiovascular%20Disease%20Prediction.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# + [markdown] id="2ihxoPWI0EOq" colab_type="text"
# #**IMPORTING THE DATASET**
#

# + id="1fUMKp8g0W0n" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 68} outputId="ca72e15f-e914-4ba0-8269-418fd197505c"
import os
os.environ['KAGGLE_USERNAME'] = "suyash091"
os.environ['KAGGLE_KEY'] = "9775b0a6da90b12a0c284d71e498de43"
# !kaggle datasets download -d sulianova/cardiovascular-disease-dataset

# + [markdown] id="2TpZrUeO49jP" colab_type="text"
# **Extracting zipfile**

# + id="6DlGlCnZ5GE3" colab_type="code" colab={}
# !unzip -q '/content/cardiovascular-disease-dataset.zip' 

# + id="MCOahQPn5n0c" colab_type="code" colab={}
import pandas as pd

# + [markdown] id="6O_kGB9B5Veb" colab_type="text"
# **Data Preprocessing**

# + id="xY2b03vQ5azX" colab_type="code" colab={}
#Fixing structure
# Read in the file
with open('/content/cardio_train.csv', 'r') as file :
  filedata = file.read()

# Replace the target string
filedata = filedata.replace(';', ',')

# Write the file out again
with open('/content/cardio_train.csv', 'w') as file:
  file.write(filedata)

# + id="EtxdlDft67IJ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 317} outputId="a3e0c948-a4cc-49fc-9135-76971380882b"
#Load Data
cvd=pd.read_csv('/content/cardio_train.csv')#.apply(lambda x: x/x.max(), axis=0)
cvd.describe()

# + id="Bg2pN04nBhi2" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 204} outputId="183a7e1c-302c-4d9f-db70-de0ea2522399"
cvd.head()

# + id="stv-zpQGE9KL" colab_type="code" colab={}
model = RandomForestClassifier(n_estimators=100)
outcome_var = ['cardio']
predictor_var = ['age', 'gender', 'height', 'weight','ap_hi','ap_lo', 'cholesterol','gluc','smoke',	'alco',	'active']

# + id="fC72kyLMGxWG" colab_type="code" colab={}
#Import models from scikit learn module:
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold   #For K-fold cross validation
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn import metrics
import numpy as np

#Generic function for making a classification model and accessing performance:
def classification_model(model, data, predictors, outcome):
  model.fit(data[predictors],data[outcome].values.ravel())
  
  predictions = model.predict(data[predictors])
  
  accuracy = metrics.accuracy_score(predictions,data[outcome])
  print('Accuracy : %s' % '{0:.3%}'.format(accuracy))

  kf = KFold(n_splits=5)
  error = []
  for train, test in kf.split(data[predictors]):
    train_predictors = (data[predictors].iloc[train,:])
    
    train_target = data[outcome].iloc[train]
    
    model.fit(train_predictors, train_target.values.ravel())
    
    error.append(model.score(data[predictors].iloc[test,:], data[outcome].iloc[test]))
 
  print('Cross-Validation Score : %s' % '{0:.3%}'.format(np.mean(error)))

  return model.fit(data[predictors],data[outcome].values.ravel())



# + id="kLLxPloyGvws" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="dbd1064c-31e9-4a78-cbc6-c27907524dfa"

#outcome_var = ['winner']
#predictor_var = ['team1', 'team2', 'venue', 'toss_winner','city','toss_decision']
history=classification_model(model, cvd,predictor_var,outcome_var)

# + id="QcPor5e7W3IZ" colab_type="code" colab={}
#inp=list(map(str,[18393,	2,	168,	62.0,	110,	80,	1,	1,	0,	0,	1]))
inp=list(map(str,'20228	1	156	85.0	140	90	3	1	0	0	1'.split()))
inp = np.array(inp).reshape((1, -1))
output=model.predict(inp)

# + id="KaxmUXeuXO1v" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="88a28a1b-e397-46c9-802e-64bd7ca96556"
print(output)

# + id="TTdumrCPUqZQ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 88} outputId="9d7ce1df-31b6-45e3-dcd0-a10f84aea734"
from sklearn.externals import joblib
joblib.dump(cvd, 'Cardiomodel.pkl')

StarcoderdataJupyterScriptsDedupFiltered