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)