Spaces:
Runtime error
Runtime error
import pandas as pd | |
import numpy as np | |
import tensorflow as tf | |
from tensorflow.keras.models import load_model | |
from sklearn.preprocessing import MinMaxScaler | |
import gradio as gr | |
import joblib | |
# Load pre-trained model and scaler | |
model = load_model('diabetes_model.h5') | |
scaler = joblib.load('scaler.pkl') | |
def predict_diabetes(pregnancies, glucose, insulin, bmi, age): | |
"""Predict diabetes probability from input features""" | |
# Create input array | |
input_data = np.array([[pregnancies, glucose, insulin, bmi, age]]) | |
# Scale features | |
scaled_data = scaler.transform(input_data) | |
# Make prediction | |
probability = model.predict(scaled_data, verbose=0)[0][0] | |
# Interpret results | |
status = "Diabetic" if probability >= 0.5 else "Not Diabetic" | |
confidence = probability if probability >= 0.5 else 1 - probability | |
# Create explanation | |
explanation = f""" | |
### Prediction: {status} | |
Confidence: {confidence:.1%} | |
#### Key factors contributing to this prediction: | |
- Glucose level: **{'High' if glucose > 140 else 'Normal'}** ({glucose} mg/dL) | |
- BMI: **{'Obese' if bmi >= 30 else 'Overweight' if bmi >= 25 else 'Normal'}** ({bmi}) | |
- Age: {age} years | |
- Insulin: {insulin} μU/mL | |
- Pregnancies: {pregnancies} | |
""" | |
# Create bar chart of feature importance | |
features = ['Pregnancies', 'Glucose', 'Insulin', 'BMI', 'Age'] | |
importance = [0.15, 0.45, 0.10, 0.20, 0.10] # Example weights | |
return { | |
"probability": float(probability), | |
"status": status, | |
"explanation": explanation, | |
"importance": (features, importance) | |
} | |
# Create Gradio interface | |
inputs = [ | |
gr.Slider(0, 15, step=1, label="Number of Pregnancies"), | |
gr.Slider(50, 200, value=120, label="Glucose Level (mg/dL)"), | |
gr.Slider(0, 300, value=80, label="Insulin Level (μU/mL)"), | |
gr.Slider(15, 50, value=32, label="BMI (kg/m²)"), | |
gr.Slider(20, 100, value=33, label="Age (years)") | |
] | |
outputs = [ | |
gr.Label(label="Diabetes Probability"), | |
gr.Markdown(label="Explanation"), | |
gr.BarPlot(x="Feature", y="Importance", label="Feature Importance") | |
] | |
title = "Diabetes Prediction App" | |
description = "Early detection of diabetes using machine learning. Based on research: Khanam, J.J. & Foo, S.Y. (2021)" | |
article = """ | |
**About this model**: | |
- Trained on Pima Indians Diabetes Dataset | |
- Neural Network with 88.6% accuracy | |
- Predicts diabetes risk using 5 key health parameters | |
""" | |
gr.Interface( | |
fn=predict_diabetes, | |
inputs=inputs, | |
outputs=outputs, | |
title=title, | |
description=description, | |
article=article, | |
examples=[ | |
[0, 90, 80, 24, 25], | |
[3, 150, 95, 32, 35], | |
[6, 180, 150, 38, 45] | |
] | |
).launch() |