DEV Community

Mate Technologies
Mate Technologies

Posted on

🧠 Building an ML-Powered BMI Risk Prediction App in Python (Step-by-Step)

In this tutorial, we’ll build BodyMetrics Pro v2.0, a desktop BMI Risk Prediction System using:

🐍 Python

πŸ–₯️ Tkinter + ttkbootstrap (modern UI)

πŸ€– Scikit-Learn (Logistic Regression)

πŸ“Š Matplotlib (visual BMI chart)

By the end, you’ll have a fully working AI-powered health app.

πŸ”— Project Repository

Clone the full project here:

https://github.com/rogers-cyber/python-tiny-tools/tree/main/BMI-prediction-system

1️⃣ What This App Does

The app:

Calculates BMI

Uses Machine Learning to predict health risk

Considers Age and Gender

Displays results visually with a BMI chart

Risk levels:

βœ… Low Risk

⚠️ Moderate Risk

❌ High Risk

2️⃣ Install Required Libraries

Before coding, install dependencies:

pip install numpy scikit-learn matplotlib ttkbootstrap

3️⃣ Import Required Modules

We start by importing all necessary libraries.

import tkinter as tk
from tkinter import messagebox
import ttkbootstrap as tb
from ttkbootstrap.constants import *
Enter fullscreen mode Exit fullscreen mode

Why?

tkinter β†’ GUI framework

ttkbootstrap β†’ modern UI themes

messagebox β†’ error alerts

Machine Learning & Math Imports

import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
Enter fullscreen mode Exit fullscreen mode

numpy β†’ numerical operations

LogisticRegression β†’ ML classifier

StandardScaler β†’ feature normalization

Charting Library

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
Enter fullscreen mode Exit fullscreen mode

This lets us embed charts inside Tkinter.

4️⃣ Building the Machine Learning Model

We encapsulate ML logic inside a class.

class BMIRiskModel:
    def __init__(self):
        self.scaler = StandardScaler()
        self.model = LogisticRegression()
        self._train()
Enter fullscreen mode Exit fullscreen mode

Why a class?

Keeps ML logic clean

Easy to reuse and maintain

Training the Model

def _train(self):
    X = np.array([
        [18, 18, 0], [22, 25, 1], [24, 30, 0],
        [27, 40, 1], [29, 45, 0], [32, 50, 1],
        [35, 55, 0], [38, 60, 1], [42, 65, 0]
    ])
Enter fullscreen mode Exit fullscreen mode

Each row contains:

[BMI, Age, Gender]

Gender:

Male = 1

Female = 0

Risk Labels

y = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2])
Enter fullscreen mode Exit fullscreen mode

0 β†’ Low Risk

1 β†’ Moderate Risk

2 β†’ High Risk

Scaling & Training

X_scaled = self.scaler.fit_transform(X)
self.model.fit(X_scaled, y)
Enter fullscreen mode Exit fullscreen mode

Scaling ensures fair ML predictions.

Making Predictions

def predict(self, bmi, age, gender):
    X = np.array([[bmi, age, gender]])
    X_scaled = self.scaler.transform(X)
    return self.model.predict(X_scaled)[0]
Enter fullscreen mode Exit fullscreen mode

5️⃣ Utility Functions
BMI Calculation

def calculate_bmi(weight, height):
    return round(weight / (height ** 2), 2)
Enter fullscreen mode Exit fullscreen mode

Risk Label Mapping

def risk_label(code):
    return {
        0: ("Low Risk", "βœ…"),
        1: ("Moderate Risk", "⚠️"),
        2: ("High Risk", "❌")
    }[code]
Enter fullscreen mode Exit fullscreen mode

6️⃣ Creating the Main Application Window

class BMIPredictorApp:
    APP_NAME = "BodyMetrics Pro"
    APP_VERSION = "2.0"
Enter fullscreen mode Exit fullscreen mode

Initialize the App

def __init__(self):
    self.root = tb.Window(themename="darkly")
    self.root.title("BodyMetrics Pro v2.0")
    self.root.minsize(720, 620)

    self.model = BMIRiskModel()
    self._build_ui()
Enter fullscreen mode Exit fullscreen mode

7️⃣ Building the User Interface
App Title

tb.Label(
    main,
    text="🧠 BodyMetrics Pro",
    font=("Segoe UI", 22, "bold")
).pack()
Enter fullscreen mode Exit fullscreen mode

Input Fields

self.weight = tb.Entry(form)
self.height = tb.Entry(form)
self.age = tb.Entry(form)
Enter fullscreen mode Exit fullscreen mode

Each input collects user data.

Gender Selection

self.gender = tk.StringVar(value="Male")

tb.Combobox(
    form,
    values=["Male", "Female"],
    textvariable=self.gender
)
Enter fullscreen mode Exit fullscreen mode

8️⃣ Analyze Button & Progress Bar

tb.Button(
    main,
    text="πŸš€ Analyze Health Risk",
    bootstyle=SUCCESS,
    command=self.analyze
).pack()

self.progress = tb.Progressbar(
    main,
    maximum=100
)
Enter fullscreen mode Exit fullscreen mode

Gives visual feedback during analysis.

9️⃣ BMI Chart Visualization

self.figure = Figure(figsize=(5, 3))
self.ax = self.figure.add_subplot(111)
Enter fullscreen mode Exit fullscreen mode

Updating the Chart

def _update_chart(self, bmi):
    self.ax.clear()
    self.ax.bar(["Your BMI"], [bmi])
    self.ax.axhline(18.5, linestyle="--")
    self.ax.axhline(25, linestyle="--")
    self.ax.axhline(30, linestyle="--")
Enter fullscreen mode Exit fullscreen mode

These lines show BMI classification zones.

πŸ”Ÿ Processing User Input

def analyze(self):
    w = float(self.weight.get())
    h = float(self.height.get())
    age = int(self.age.get())
Enter fullscreen mode Exit fullscreen mode

Predicting Risk

bmi = calculate_bmi(w, h)
risk_code = self.model.predict(bmi, age, gender)
label, icon = risk_label(risk_code)

Display Result
self.result.config(
    text=f"{icon} BMI: {bmi} | {label}",
    font=("Segoe UI", 16, "bold")
)
Enter fullscreen mode Exit fullscreen mode

πŸ”š Running the App

if __name__ == "__main__":
    app = BMIPredictorApp()
    app.run()
Enter fullscreen mode Exit fullscreen mode

πŸŽ‰ Final Result

You now have:

βœ… A modern desktop GUI

πŸ€– An ML-based BMI risk predictor

πŸ“Š Interactive BMI visualization

🧩 Clean, modular Python code

Top comments (0)