Site icon DataFlair

Deep Learning Project – Heart Disease Predictor using ANN

Machine Learning courses with 110+ 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).

| Feature      | Meaning                     | Example |
| ------------ | --------------------------- | ------- |
| Age          | Person's age                | 45      |
| RestingBP    | Resting Blood Pressure      | 130     |
| Cholesterol  | Cholesterol level           | 250     |
| MaxHR        | Maximum heart rate achieved | 140     |
| Oldpeak      | ST depression (ECG data)    | 2.5     |
| HeartDisease | Target (0=no, 1=yes)        | 1       |
"""

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.metrics import classification_report, confusion_matrix
import matplotlib.pyplot as plt

# Load dataset
data = {
    'Age': [29, 45, 58, 34, 60, 50, 40, 66, 55, 38],
    'RestingBP': [120, 130, 140, 110, 150, 145, 135, 160, 155, 125],
    'Cholesterol': [200, 250, 240, 180, 290, 275, 230, 300, 310, 220],
    'MaxHR': [150, 140, 135, 160, 130, 125, 145, 120, 115, 155],
    'Oldpeak': [1.0, 2.5, 3.0, 0.5, 4.0, 3.5, 2.0, 5.0, 4.5, 1.5],
    'HeartDisease': [0, 1, 1, 0, 1, 1, 0, 1, 1, 0]
}
df = pd.DataFrame(data)
df.shape

# Split features and target
X = df.drop('HeartDisease', axis=1) # Independed

y = df['HeartDisease'] # Depended
y.head()

# Normalize data
scaler = MinMaxScaler()
X_scaled = scaler.fit_transform(X)
X_scaled

# Split data
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)

# Build ANN model
model = Sequential()
model.add(Dense(10, activation='relu', input_shape=(X.shape[1],))) # Input+hidden
model.add(Dense(5, activation='relu'))
model.add(Dense(1, activation='sigmoid'))  # output layer for binary classification

# Compile model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

# Train model
history = model.fit(X_train, y_train, validation_split=0.2, epochs=200, verbose=0)

# Evaluate model
loss, accuracy = model.evaluate(X_test, y_test)
print("Test Accuracy: {:.2f}%".format(accuracy * 100))

# Make predictions
y_pred = model.predict(X_test)
y_pred_classes = (y_pred > 0.5).astype(int)
y_pred
y_pred_classes

# Confusion Matrix & Report
print("\nConfusion Matrix:")
print(confusion_matrix(y_test, y_pred_classes))
print("\nClassification Report:")
print(classification_report(y_test, y_pred_classes))

new_data = np.array([[50, 140, 250, 130, 2.5]])
new_data_scaled = scaler.transform(new_data)
prediction = model.predict(new_data_scaled)
result = (prediction > 0.5).astype(int)
print("Heart Disease Present?" , result)

 

 

Exit mobile version