Deep Learning Project – Heart Disease Predictor using ANN Part – 2
Machine Learning courses with 100+ Real-time projects Start Now!!
Program 1
Heart Disease Predictor using ANN (Keras)
We want to predict whether a person has heart disease or not based on multiple health parameters. This is a binary classification problem (0 = No disease, 1 = Disease).
| Column | Description |
| -------- | ------------------------------------------------------- |
| age | Age |
| sex | 1 = male; 0 = female |
| cp | Chest pain type (0-3) |
| trestbps | Resting blood pressure |
| chol | Serum cholesterol |
| fbs | Fasting blood sugar (> 120 mg/dl) (1 = true; 0 = false) |
| restecg | Resting electrocardiographic results |
| thalach | Maximum heart rate achieved |
| exang | Exercise induced angina |
| oldpeak | ST depression induced by exercise |
| slope | Slope of the peak exercise ST segment |
| ca | Major vessels (0-3) colored by fluoroscopy |
| thal | 1 = normal; 2 = fixed defect; 3 = reversible defect |
| target | 0 = no disease, 1 = disease |
# Import Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import confusion_matrix, classification_report
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# Load Dataset
df = pd.read_csv("D://scikit_data/heart/heart.csv")
df.isnull().sum()
# Data Preprocessing
# Split features and target
X = df.drop('target', axis=1)
y = df['target']
X.head()
y.head()
df.shape
# Scale features between 0 and 1
scaler = MinMaxScaler()
X_scaled = scaler.fit_transform(X)
# Split into train-test
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
len(X_train)
len(X_test)
# Build ANN Model
model = Sequential()
# Input layer
model.add(Dense(32, activation='relu', input_shape=(X.shape[1],))) # Input + First Hidden
# Hidden layers
model.add(Dense(16, activation='relu')) # Second Hidden
model.add(Dense(8, activation='relu')) # Thrid Hidden
# Output layer (binary classification)
model.add(Dense(1, activation='sigmoid')) # Output
# Compile the model
model.compile(
optimizer='adam', # How model learns
loss='binary_crossentropy', # How model calculates error
metrics=['accuracy'] # What performance you want to track
)
# Train the model
history = model.fit(X_train, y_train, validation_split=0.2, epochs=100, verbose=0)
# Plot Loss Graph
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Loss Over Epochs')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
# Evaluate Model
loss, accuracy = model.evaluate(X_test, y_test)
print(f"\nTest Accuracy: {accuracy*100:.2f}%")
# Predictions
y_pred = model.predict(X_test)
y_pred
y_pred_classes = (y_pred > 0.5).astype(int)
y_pred_classes
# Confusion Matrix & Classification Report
cm = confusion_matrix(y_test, y_pred_classes)
print("\nConfusion Matrix:\n", cm)
cr = classification_report(y_test, y_pred_classes)
print("\nClassification Report:\n", cr)
# Visualize Confusion Matrix
plt.figure(figsize=(5, 5))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')
plt.xlabel('Predicted')
plt.ylabel('Actual')
plt.title('Confusion Matrix')
plt.show()
new_data = np.array([[48,1,1,90,123,1,0,162,0,1.1,2,1,1]])
new_data_scaled = scaler.transform(new_data)
prediction = model.predict(new_data_scaled)
result = (prediction > 0.5).astype(int)
print("Heart Disease Present?" , result)
Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

