πŸ‘οΈ Myopia Risk Prediction (MyopiaGuard)

Models behind MyopiaGuard, a final-year academic project that screens children and teenagers for myopia (nearsightedness) risk using questionnaire data: age, screen time, near work, outdoor time, family history, school type, state and more.

The deployed system runs a three-stage pipeline:

  1. Stage 1: Does the person likely have a refractive error? (XGBoost classifier)
  2. Stage 2: How high is the progression risk? (Gradient Boosting classifier, blended with evidence-based clinical rules)
  3. Stage 3: Rough diopter estimate, only when Stage 1 says yes (Random Forest regressor)

⚠️ Not a medical device. This is a student project for education and research. It doesn't replace an eye examination by an optometrist or ophthalmologist.


🧠 Models

File Model Task Test metric (1,000 held-out samples)
models/has_re_model_improved.pkl XGBoost Stage 1: has refractive error (yes/no) ROC-AUC 0.945
models/risk_progression_model.pkl GradientBoosting (monotone constraints) Stage 2: high vs low/moderate progression risk ROC-AUC 0.894
models/diopter_regression_model.pkl RandomForestRegressor Stage 3: absolute diopter estimate MAE 1.71 D, RMSE 2.09 D, RΒ² βˆ’0.09
models/myopia_image_classifier.keras MobileNetV2 (Keras) Eye image: Myopia vs Normal 99.7% accuracy (reported)
models/myopia_classifier.onnx ONNX export of the above Same, portable runtime same as above

Preprocessing files

File Used with
models/has_re_scaler.pkl + models/has_re_features.json Stage 1 model (29 features)
models/scaler_classification.pkl + models/feature_columns.json Stage 2 model (30 features)
models/scaler_regression.pkl Stage 3 model (27-feature subset, listed in backend/api.py)
models/model_metadata.json Training date, sklearn version, all metrics

models/has_re_model.pkl is the older Stage 1 model, kept for comparison.


πŸš€ How to use

Option 1: Call the live API (easiest)

curl -X POST https://unnati14-myopia-risk-api.hf.space/predict \
  -H "Content-Type: application/json" \
  -d '{"age": 12, "sex": "male", "height": 150, "weight": 40,
       "screenTime": 6, "nearWork": 4, "outdoorTime": 1, "sports": "occasional",
       "familyHistory": true, "parentsMyopic": "one", "state": "Gujarat",
       "locationType": "urban", "schoolType": "private",
       "tuition": true, "competitiveExam": false, "vitaminD": false}'

Example response:

{"risk_score": 59, "risk_level": "MODERATE", "risk_probability": 0.593,
 "has_re": true, "re_probability": 0.94, "diopters": 3.43, "severity": "Moderate"}

The free Space sleeps when idle, so the first request after a while can take about a minute.

Option 2: Load the models in Python

The models expect engineered features (e.g. Age_Screen, Screen_Outdoor_Ratio, one-hot State_* columns). The code that builds them from raw answers is in backend/api.py (build_stage1_features, build_feature_row).

import json
import joblib
import pandas as pd
from huggingface_hub import hf_hub_download

REPO = "unnati14/myopia-risk-prediction"
get = lambda f: hf_hub_download(REPO, f"models/{f}")

# Stage 1: has refractive error?  (model + its own scaler + its own feature list)
re_model  = joblib.load(get("has_re_model_improved.pkl"))
re_scaler = joblib.load(get("has_re_scaler.pkl"))
re_cols   = json.load(open(get("has_re_features.json")))["feature_columns"]

# One row of engineered features, columns in exactly this order
row = pd.DataFrame([your_feature_dict])[re_cols]
prob = re_model.predict_proba(re_scaler.transform(row))[0][1]
print(f"P(refractive error) = {prob:.2f}")

Load with joblib, and use the same library versions the models were trained with: scikit-learn 1.7.2 and xgboost 3.2.0.

Image classifier (Keras / ONNX)

import numpy as np
import onnxruntime as ort
from huggingface_hub import hf_hub_download

path = hf_hub_download("unnati14/myopia-risk-prediction", "models/myopia_classifier.onnx")
session = ort.InferenceSession(path)
img = np.expand_dims(your_image / 255.0, axis=0).astype(np.float32)  # (1, 224, 224, 3)
out = session.run(None, {session.get_inputs()[0].name: img})
print("Myopia" if out[0][0][0] > 0.5 else "Normal")

πŸ“Š Dataset

  • File: data/Myopia_Dataset_5000.csv
  • Samples: 5,000 (4,000 train / 1,000 test)
  • Features: age, sex, height, weight, BMI, state, urban/rural, school type, family history, parents with myopia, screen time, near-work hours, outdoor time, tuition, competitive-exam prep, vitamin D, sports
  • Targets: Presence_of_RE, Degree_RE_Diopters, Progression_Risk

⚠️ Limitations

  • Stage 3 (diopter estimate) has RΒ² below zero on the test set, so it doesn't yet beat predicting the average. Treat its number as a rough indication only. The API falls back to rule-based estimates if the model can't load.
  • Stage 2's final risk score blends the model with clinical rules, so the API's risk score isn't the raw model output.
  • The data covers Indian states only. Results may not transfer to other populations.
  • .pkl files are Python pickles. Only load pickles from sources you trust.

🏫 Project info

Field Details
Project Myopia Risk Prediction System (Project III, 6th semester)
Models XGBoost, Gradient Boosting, Random Forest, MobileNetV2
Backend Python, Flask (hosted on Hugging Face Spaces)
Frontend React + Vite (hosted on Vercel)

πŸ“„ License

MIT, for academic and research use.

Downloads last month
-
Inference Providers NEW
This model isn't deployed by any Inference Provider. πŸ™‹ Ask for provider support

Space using unnati14/myopia-risk-prediction 1