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

# +
# Import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from keras.utils import to_categorical

# Import data
url = r'http://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/processed.cleveland.data'
dataframe = pd.read_csv(url, 
                        sep = ',', 
                        header = None, 
                        index_col = None,
                        na_values = '?')

# Add column names
name_list = ['age', 'sex', 'cp','trestbps', 'chol', 'fbs','restecg',
             'thalac','exang','oldpeak','slope','ca','thal','num']
dataframe.columns = name_list

# Fill missing data with columnwise median values
dataframe = dataframe.fillna(dataframe.median())


# Select the data (input) columns
data_list = ['age', 'sex', 'cp','trestbps', 'chol', 'fbs','restecg',
             'thalac','exang','oldpeak','slope','ca','thal']
data = dataframe[data_list]

# Scale the data
data_min = data.min()
data_max = data.max()
data_norm = (data - data_min)/(data_max - data_min)

# Another way to scale
#from sklearn.preprocessing import MinMaxScaler
#scaler = MinMaxScaler()
#data_norm = scaler.fit_transform(data.values)

# Save the data
#np.save('case_1_data.npy', data_norm)

# Select the labels (output)
labels = dataframe['num']

# Code labels to categorical output
one_hot_labels = to_categorical(labels)

# Save categorical (one hot coded) labels
#np.save('case_1_one_hot_labels.npy', one_hot_labels)

# Save binary labels
#np.save('case_1_bin_labels.npy', bin_labels)

# +
#test_data = data_norm[:200]
#val_data = data_norm[200:]
#test_labels = bin_labels[:200]
#val_labels = bin_labels[200:]
from sklearn.model_selection import train_test_split

train_data,val_data,train_label,val_label = train_test_split(data_norm,
                                                               bin_labels,
                                                               test_size=0.26,
                                                               random_state=42)
len(train_data),len(val_data)

# +
from keras.models import Sequential
from keras.layers import Dense
import time

start = time.time()

model = Sequential()
model.add(Dense(39,activation='relu', input_dim=13))
model.add(Dense(19,activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop',
             loss='binary_crossentropy',
             metrics=['accuracy'])
history = model.fit(train_data,
                    train_label,
                    epochs=300,
                    batch_size=200,
                    verbose=1,
                    validation_data=(val_data,val_label)
                   )

end = time.time()

h_dict = history.history
epochs = range(1, len(h_dict['loss'])+1)

plt.plot(epochs, h_dict['loss'], 'bo', label='Training loss')
plt.plot(epochs, h_dict['val_loss'], 'b', label='Validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
print(h_dict['val_loss'][len(h_dict['val_loss'])-1])

print('time', end - start)

# +
plt.plot(epochs, h_dict['acc'], 'bo', label='Training acc')
plt.plot(epochs, h_dict['val_acc'], 'b', label='Validation acc')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.show()

print(h_dict['val_acc'][len(h_dict['val_acc'])-1])
# -



StarcoderdataJupyterScriptsDedupFiltered