it-it / app.py
hari6677's picture
Create app.py
bd46d4d verified
import joblib
import numpy as np
import pandas as pd
import gradio as gr
# --- 1. Load Model and Features ---
# Ensure these two files are uploaded to your Hugging Face Space folder!
try:
model = joblib.load('ckd_model.joblib')
# This list ensures input fields are created and data is fed in the correct order (24 features)
FEATURE_COLUMNS = joblib.load('model_features.joblib')
except FileNotFoundError:
raise FileNotFoundError("Model or feature files not found. Ensure 'ckd_model.joblib' and 'model_features.joblib' are uploaded.")
# --- 2. Define the Prediction Function ---
def predict_ckd(*inputs):
"""
Takes 24 inputs (features) from the Gradio interface and returns the prediction.
"""
# Convert inputs (which come as a tuple from Gradio) into a NumPy array
# and reshape it to match the model's required input format (1 sample, 24 features)
input_data = np.array(inputs).reshape(1, -1)
# 1. Make the raw prediction (0 or 1)
prediction = model.predict(input_data)[0]
# 2. Get the probability for the "Not CKD" class (class 1)
# This is often more informative than just a 0/1 result
probability_not_ckd = model.predict_proba(input_data)[0][1]
# Determine the final output text and confidence
if prediction == 0:
result_text = "Positive for Chronic Kidney Disease (CKD)"
confidence = 1 - probability_not_ckd # Confidence in CKD
color = "red"
else: # prediction == 1
result_text = "Negative for Chronic Kidney Disease (CKD)"
confidence = probability_not_ckd # Confidence in Not CKD
color = "green"
# Return prediction with formatted confidence
return f"<h2 style='color: {color};'>Prediction: {result_text}</h2><p>Confidence: {confidence:.2f} ({confidence*100:.0f}%)</p>"
# --- 3. Create the Gradio Interface Components ---
# Dynamically generate the 24 input components based on the feature list
input_components = []
for feature in FEATURE_COLUMNS:
# Use a generic Textbox for input, as Gradio will automatically handle numeric types
# You might customize these later (e.g., using gr.Slider for age, gr.Radio for binary inputs)
input_components.append(gr.Textbox(label=feature.upper(), placeholder=f"Enter value for {feature}"))
# --- 4. Launch the Gradio Interface ---
# The output component is set to HTML to allow for colored text output
output_component = gr.HTML(label="Prediction Result")
# Combine the function, inputs, and outputs into a Gradio interface
iface = gr.Interface(
fn=predict_ckd,
inputs=input_components,
outputs=output_component,
title="CKD Prediction Model (Random Forest)",
description="Enter the 24 clinical parameters below to predict the risk of Chronic Kidney Disease. **Note: For binary features (yes/no, present/notpresent), use the encoded numerical values (0 or 1) used during training.**"
)
# Launch the app (Hugging Face Spaces runs this automatically)
iface.launch(share=False)