In my Random Forests post, we covered how a forest of decision trees votes on a prediction. This post puts that to work: FitXAI is a workout coach that gives you a personalized plan and shows you why it picked each part of it.
🎯 The Idea
Most fitness apps are black boxes. You enter your info, get a plan, and have no idea why it chose those exercises or that split. FitXAI combines three things to fix that:
- Machine learning for the recommendations (a Random Forest ensemble)
- SHAP values to show which inputs drove each recommendation
- An LLM to turn that into plain-English coaching notes
🏗️ System Architecture
Core Components
The key piece is the function that turns raw SHAP output into something readable:
# Main prediction pipeline
def create_aggregated_explanation(shap_values, feature_names, input_transformed, target_idx=0):
"""Create aggregated SHAP explanation with human-readable features"""
# Process multi-output SHAP values
# Aggregate one-hot encoded features
# Generate human-readable explanations
Data Schema
The model takes 8 inputs:
FEATURE_COLS = [
'height_cm', # User height
'physique_idx', # Body type (-0.5 to 0.5)
'exp_idx', # Experience level (0.1 to 0.8)
'joint_health', # Joint health (1-10 scale)
'stress_idx', # Stress level (1-10 scale)
'avail_min', # Available workout time
'equip_lvl', # Equipment access (0-2)
'goal_id' # Primary goal (0-2)
]
A preprocessing pipeline scales the numeric columns, one-hot encodes the categorical ones, and does some feature engineering on top.
That’s a lot of data processing, which is normal for ML, but this project had an extra wrinkle. My data didn’t have one “target” like most online courses or college assignments. I needed a multi-output Random Forest that predicts 5 things at once, which meant breaking the inputs apart with the steps above and then aggregating the output back into something a person can read. I’ll probably go deeper on this another time, maybe with a video on my channel.
🤖 The Random Forest Ensemble
Multi-Output Architecture
Instead of a single-output classifier, FitXAI uses a multi-output Random Forest that predicts 5 dimensions at once:
{
'workout_split': 2, # PPL, Full Body, or Upper/Lower
'training_modality': 1, # Machines, Calisthenics, or Weights
'cardio_approach': 0, # None, LISS, or HIIT
'intensity_level': 1, # Low, Medium, or High
'rest_days': 2 # Number of rest days per week
}
Predicting them together keeps the plan coherent: the outputs are learned jointly instead of by five separate models that might disagree.
Why a Forest and Not One Tree
Compared to a single decision tree, the forest gives you less overfitting (thanks to bootstrap aggregation), built-in feature importance, better tolerance for outliers and noisy data, and training that parallelizes easily.
🧠 Explainable AI Implementation
SHAP Integration
The transparency comes from SHAP (SHapley Additive exPlanations), which shows how much each input pushed a recommendation one way or the other:
# Create SHAP explanations for each prediction
explainer = shap.TreeExplainer(model.named_steps['classifier'])
shap_values = explainer.shap_values(input_transformed)
# Generate human-readable explanations
clean_exp, final_names, agg_vals, agg_data = create_aggregated_explanation(
shap_values, transformed_names, current_transformed, target_idx
)
('classifier' is the Random Forest itself.)
Aggregating One-Hot Features
One annoying thing about SHAP: it scores each one-hot column separately, so “Equipment” shows up as three confusing features. I group them back together:
# Define feature groups for aggregation
ohe_groups = {
"Equipment": {
"features": [f for f in feature_names if "equip_lvl" in f],
"labels": EQUIPMENT_LABELS
},
"Goal": {
"features": [f for f in feature_names if "goal_id" in f],
"labels": GOAL_LABELS
}
}
That gives you explanations like “Equipment: Full Gym increases recommendation” instead of raw one-hot values.
Full transparency: I got this aggregation working for the first chart (the waterfall), but not for the second bar graph below it. It ain’t easy!
🎨 User Interface
Streamlit
The whole app is Streamlit, which made it quick to build and deploy:
# Page configuration for optimal user experience
st.set_page_config(
page_title="FitXAI Coach",
layout="centered",
initial_sidebar_state="expanded"
)
Custom Visualization
I didn’t like the built-in SHAP waterfall plots (they’re brittle), so I wrote my own:
def create_custom_waterfall_chart(feature_names, shap_values, data_values):
"""Create custom horizontal bar chart to replace brittle SHAP waterfall"""
fig, ax = plt.subplots(figsize=(12, 8))
# Sort features by absolute SHAP impact
sorted_indices = np.argsort(np.abs(shap_values))[::-1]
sorted_shap = np.asarray(shap_values)[sorted_indices]
y_pos = np.arange(len(sorted_shap))
# Create horizontal bars with color coding
colors = ['#2ecc71' if v > 0 else '#e74c3c' for v in sorted_shap]
bars = ax.barh(y_pos, sorted_shap, align='center', color=colors, alpha=0.8)
Layers of Explanation
Each result comes with SHAP charts showing feature impact, an AI coach summary from the LLM, a weekly workout schedule with exercises, and a downloadable report.
🔧 Technical Challenges
Multi-Output SHAP
For multi-output models, SHAP can hand back a list of arrays, and between all my mappings, targets and features it got confusing fast. This is the extraction that works:
# Correct multi-output extraction
if isinstance(shap_values, list):
vals = shap_values[target_idx][0]
else:
vals = shap_values[0, :, target_idx]
Input Validation
Inputs are validated with Pydantic:
class FitnessInput(BaseModel):
height_cm: float
physique_idx: float
exp_idx: float
@validator('height_cm')
def validate_height(cls, v):
if not 100 <= v <= 250:
raise ValueError('Height must be between 100-250 cm')
return v
Caching
Streamlit’s caching gave me some trouble at first, but it works well now. I leaned on snippets I found in other projects:
@st.cache_resource
def load_model():
"""Cache model loading for performance"""
return joblib.load('fitness_model.joblib')
🚀 Deployment
Hugging Face Spaces
The app runs on Hugging Face Spaces. Streamlit apps deploy there with basically no config, the Space is version-controlled, and it’s easy to share.
Data Collection
The app saves anonymized inputs and predictions:
def save_user_data(user_inputs, predictions):
"""Save user input data and predictions to CSV"""
with open(csv_file, 'a', newline='') as f:
writer = csv.writer(f)
writer.writerow([datetime.now().isoformat(), ...])
That data can be used to keep improving the model while keeping users anonymous.
Key Learnings
What worked: Multi-output Random Forests gave coherent plans. SHAP explanations make the recommendations easier to trust. Streamlit made prototyping and deployment fast. Aggregating one-hot features made the model readable.
What was hard:
- SHAP’s built-in plots were brittle. Fixed with custom charts.
- Multi-output explanations. Fixed with careful indexing, but aggregation on the second chart is still an open problem.
- UI stability. Fixed with a lot of CSS.
- Data preprocessing. Fixed with a proper pipeline.
Future Ideas
Progress tracking over time, learning from user feedback, wearable integration, workout sharing, and better visualizations.
Try It Yourself
FitXAI is free at https://huggingface.co/spaces/william-ai-dev/fit-xai. Plug in your info and you’ll get a plan, the explanation behind it, and a downloadable copy. The full source (training pipeline, SHAP integration, custom charts and Streamlit UI) is in the Space repository.
Takeaway: If your model’s output affects what someone does, show them why. A Random Forest plus SHAP is one of the cheapest ways to get there. And I think any engineer who wants to work in AI should be able to explain how their model works under the hood, and prove it.