This image shows the first thing users see when they enter the Heart Disease calculator. It asks for some simple questions that users can answer to get a general idea of their risk of heart disease.

This image shows how I unputed data to get a prediction. I have filled every field based on my doctor’s report, and now I can press the “Predict Heart Disease” button.

This image shows what is displayed when I click the button. It displays a message that says “Likelihood of Heart Disease: Low.”

from flask import Flask, request, jsonify
from flask import Blueprint
from flask_restful import Api, Resource
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

heart_disease_data = pd.read_csv('/home/jared/vscode/JaredsBlogBE/data/DatasetHeartDisease.csv')  # Update path to your heart disease dataset


X = heart_disease_data[['age', 'sex', 'chest pain type', 'resting bps', 'cholesterol', 'fasting blood sugar',
                        'resting ecg', 'max heart rate', 'exercise angina', 'oldpeak', 'ST slope']]
y = heart_disease_data['target']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

logreg = LogisticRegression(max_iter=1000)
logreg.fit(X_train_scaled, y_train)

heart_disease_api = Blueprint('heart_disease_api', __name__, url_prefix='/api/heart_disease')
api = Api(heart_disease_api)

class HeartDiseaseAPI(Resource):
    def predict_heart_disease(self, data):
        try:
            # Prepare data for prediction
            input_data = pd.DataFrame([data])
            input_data_scaled = scaler.transform(input_data)

            # Predict the outcome
            prediction = logreg.predict(input_data_scaled)

            return {'Prediction': int(prediction[0])}  # Assuming 1 for heart disease, 0 for no heart disease

        except Exception as e:
            return {'error': str(e)}

    def post(self):
        try:
            data = request.json
            result = self.predict_heart_disease(data)
            return jsonify(result)
        except Exception as e:
            return jsonify({'error': str(e)})

api.add_resource(HeartDiseaseAPI, '/predict')

This is the backend code. This code sets up a Flask API to predict heart disease likelihood based on health attributes. It begins by loading a dataset containing information like age, sex, and cholesterol levels. After splitting the data into training and testing sets, it standardizes the features for consistency. Using logistic regression, a common classification algorithm, the model is trained on the scaled data to predict heart disease. The API, configured with a /predict endpoint, accepts input data in JSON format, scales it accordingly, and returns the prediction result indicating the likelihood of heart disease.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Heart Disease Prediction</title>
</head>
<body>
    <h1>Heart Disease Prediction</h1>
    <form id="heartDiseaseForm">
        <label for="age">Age:</label>
        <input type="number" id="age" name="age" required><br><br>
        <label for="sex">Sex:</label>
        <select id="sex" name="sex" required>
            <option value="1">Male</option>
            <option value="0">Female</option>
        </select><br><br>
        <label for="chestPainType">Chest Pain Type:</label>
        <select id="chestPainType" name="chestPainType" required>
            <option value="1">Typical Angina</option>
            <option value="2">Atypical Angina</option>
            <option value="3">Non-anginal Pain</option>
            <option value="4">Asymptomatic</option>
        </select><br><br>
        <label for="restingBPS">Resting Blood Pressure (mm Hg):</label>
        <input type="number" id="restingBPS" name="restingBPS" required><br><br>
        <label for="cholesterol">Cholesterol (mg/dl):</label>
        <input type="number" id="cholesterol" name="cholesterol" required><br><br>
        <label for="maxHeartRate">Max Heart Rate:</label>
        <input type="number" id="maxHeartRate" name="maxHeartRate" required><br><br>
        <label for="exerciseAngina">Exercise Induced Angina:</label>
        <select id="exerciseAngina" name="exerciseAngina" required>
            <option value="0">No</option>
            <option value="1">Yes</option>
        </select><br><br>
        <label for="oldpeak">ST Depression Induced by Exercise Relative to Rest:</label>
        <input type="number" id="oldpeak" name="oldpeak" step="0.01" required><br><br>
        <button type="button" onclick="predictHeartDisease()">Predict Heart Disease</button>
    </form>
    <div id="predictionResult"></div>
    <script>
        function predictHeartDisease() {
            var form = document.getElementById('heartDiseaseForm');
            var predictionResult = document.getElementById('predictionResult');
            var formData = new FormData(form);
            fetch('http://localhost:8084/api/heart_disease/predict', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify(Object.fromEntries(formData))
            })
            .then(response => response.json())
            .then(data => {
                var predictionMessage;
                if (data['Prediction'] === 1) {
                    predictionMessage = 'Likelihood of Heart Disease: High';
                } else {
                    predictionMessage = 'Likelihood of Heart Disease: Low';
                }
                predictionResult.innerText = predictionMessage;
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }
    </script>
</body>
</html>

This is the backend code. This code creates a webpage for predicting the chance of heart disease. It has a form where you can enter your age, sex, chest pain type, blood pressure, cholesterol, heart rate, angina status, and ST depression. When you click the “Predict Heart Disease” button, it sends this information to the backend. That program calculates the likelihood of heart disease and sends the result back. Then, the webpage shows a message saying if the chance of heart disease is high or low based on what the program says.