← Back to recipes

Route service users to appropriate support

service-deliveryintermediateemerging

The problem

Service users get routed to the wrong support and everyone wastes time. Someone needing crisis intervention gets put in a general support group. Someone ready for peer support gets intensive one-to-one. Misallocation means: worse outcomes (wrong service for their needs), wasted capacity (intensive services used inefficiently), delays (reassessment and re-routing takes weeks). You're making triage decisions based on gut feel without consistent criteria.

The solution

Build a classification model that learns from your successful referrals. It analyses patterns: what combination of needs, circumstances, severity indicators, and support history led to good outcomes in each service type? New referrals get scored for fit with each pathway. The model suggests: 'Crisis intervention (85% confidence) based on: risk indicators, previous engagement, current circumstances'. Human professionals review the recommendation and make the final decision.

What you get

For each new referral, a recommended pathway with confidence score: 'Suggested: Peer support group (75% match). Reasoning: stable housing, previous positive group experience, moderate support needs, ready for independence. Alternative: One-to-one support (60% match) if personal circumstances change.' Professional reviews recommendation, considers context the model can't see, makes final decision. Faster, more consistent triage.

Before you start

  • Historical referral data: needs assessment, circumstances, pathway allocated, outcomes
  • At least 100-200 referrals across your pathways (model needs training data)
  • Clear definition of what makes a successful referral for each pathway
  • Lawful basis under GDPR to process service user data for service improvement
  • Professional oversight - this supports decisions, doesn't replace professional judgement
  • A Google account for Colab
  • Basic Python skills or willingness to adapt example code

When to use this

  • You have multiple support pathways and struggle to allocate people consistently
  • Misallocation is common and causes poor outcomes or wasted capacity
  • You've got enough historical data to identify what works
  • You want to support professionals with better triage, not replace their judgement

When not to use this

  • You have only one service pathway - nothing to choose between
  • You don't have historical outcome data - model needs to learn what success looks like
  • Your pathways change frequently - model becomes outdated
  • You can't commit to human oversight of every recommendation - automated decisions affecting vulnerable people are dangerous
  • Data quality is poor (missing assessments, inconsistent recording)

Steps

  1. 1

    Define successful referrals

    For each pathway, what does success look like? Completed programme? Positive outcome scores? Sustained engagement? You need to train the model on 'these referrals worked well, these didn't'. Be specific and measurable. If you can't define success, you can't build a model.

  2. 2

    Gather historical referral data

    Extract: needs assessment data (risk factors, support needs, circumstances), demographics, previous service use, pathway allocated, outcomes achieved. You need both the inputs (assessment) and outputs (which pathway, how it went). Minimum 100-200 referrals, ideally more.

  3. 3

    Identify predictive features

    What factors predict good fit? Risk level, housing status, previous engagement, support network strength, specific needs (mental health, substance use, employment). Don't include protected characteristics (race, gender) unless there's a legitimate reason and legal basis. Focus on needs and circumstances that determine service suitability.

  4. 4

    Label your training data

    For historical referrals, mark whether the pathway allocation was successful: 'yes' if they completed/benefited, 'no' if they dropped out, were unsuitable, or got poor outcomes. This trains the model to recognise: what patterns predicted good vs poor pathway fit.

  5. 5

    Build the classification model

    Use Random Forest (the example code) to learn which features predict success in each pathway. The model identifies patterns: 'Service users with stable housing + previous positive group experience + moderate needs → 85% success rate in peer support groups'. It's learning from your historical decisions that worked.

  6. 6

    Validate the model

    Test on referrals the model hasn't seen: does it correctly predict which pathway would work best? If accuracy is below 70%, you might need more data, different features, or your historical allocations weren't consistent enough to learn from. Check it makes professional sense.

  7. 7

    Generate recommendations with explanations

    For new referrals, the model suggests pathways with confidence scores and reasoning: 'Crisis intervention (85%) because: high risk indicators, unstable housing, previous crisis response worked'. Explanations are critical - professionals need to understand the recommendation to evaluate it.

  8. 8

    Implement with human oversight

    Critical: professionals must review every recommendation. The model spots patterns and suggests, humans consider context the model can't see (family situation just changed, cultural factors, professional intuition). Never route automatically. This supports professional judgement, doesn't replace it.

  9. 9

    Track and refine(optional)

    Monitor: when professionals override recommendations, why? Were they right? Is the model missing important factors? Retrain monthly with new referrals and outcomes. The model improves as it learns from more decisions and their results.

Example code

Classify referrals to support pathways

This builds a model to recommend appropriate support pathways. Adapt the features to your service model and needs assessment.

import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix

# Load historical referral data
# Columns: referral_id, assessment features, pathway_allocated, outcome_success
referrals = pd.read_csv('historical_referrals.csv')

print(f"Loaded {len(referrals)} historical referrals")
print(f"Pathways: {referrals['pathway_allocated'].unique()}")
print(f"Success rate: {referrals['outcome_success'].mean()*100:.1f}%")

# Define features that predict pathway suitability
# Adapt these to your needs assessment and service model
feature_cols = [
    'risk_level',  # 1-5 scale
    'housing_stable',  # 0/1
    'support_network_strength',  # 1-5 scale
    'previous_service_completion',  # 0/1
    'mental_health_needs',  # 0/1
    'substance_use_needs',  # 0/1
    'employment_needs',  # 0/1
    'crisis_indicators',  # 0/1
    'ready_for_group_work',  # 0/1
    'months_since_last_service'  # numeric
]

# Prepare data
X = referrals[feature_cols]
y = referrals['pathway_allocated']  # The pathway they were allocated to

# Filter to successful referrals only for training
# We want to learn patterns of successful allocations
successful_referrals = referrals[referrals['outcome_success'] == 1]
X_successful = successful_referrals[feature_cols]
y_successful = successful_referrals['pathway_allocated']

print(f"\nTraining on {len(successful_referrals)} successful referrals")

# Split into train/test
X_train, X_test, y_train, y_test = train_test_split(
    X_successful, y_successful,
    test_size=0.3,
    random_state=42,
    stratify=y_successful  # Ensure all pathways represented
)

# Train Random Forest classifier
rf = RandomForestClassifier(
    n_estimators=100,
    max_depth=10,
    random_state=42,
    class_weight='balanced'  # Handle imbalanced pathways
)
rf.fit(X_train, y_train)

# Evaluate
y_pred = rf.predict(X_test)
print("\nModel Performance:")
print(classification_report(y_test, y_pred))

# Confusion matrix shows which pathways get confused
print("\nConfusion Matrix:")
print(confusion_matrix(y_test, y_pred))

# Feature importance
feature_importance = pd.DataFrame({
    'feature': feature_cols,
    'importance': rf.feature_importances_
}).sort_values('importance', ascending=False)

print("\nMost important factors for pathway recommendations:")
print(feature_importance.head(10))

# Function to recommend pathway for new referral
def recommend_pathway(assessment_data):
    """
    Generate pathway recommendation with confidence and explanation
    assessment_data: dict with feature values
    """
    # Convert to format model expects
    features = [assessment_data[col] for col in feature_cols]
    features_array = np.array(features).reshape(1, -1)

    # Get probabilities for each pathway
    pathways = rf.classes_
    probabilities = rf.predict_proba(features_array)[0]

    # Get top recommendation
    top_idx = np.argmax(probabilities)
    recommended_pathway = pathways[top_idx]
    confidence = probabilities[top_idx] * 100

    # Get alternative
    sorted_indices = np.argsort(probabilities)[::-1]
    alternative_idx = sorted_indices[1]
    alternative_pathway = pathways[alternative_idx]
    alternative_confidence = probabilities[alternative_idx] * 100

    # Identify key factors driving recommendation
    # Which features contributed most to this decision
    feature_values = pd.DataFrame({
        'feature': feature_cols,
        'value': features,
        'importance': rf.feature_importances_
    })

    # Features that are "active" (high value) and important
    feature_values['contribution'] = feature_values['value'] * feature_values['importance']
    top_factors = feature_values.nlargest(3, 'contribution')

    recommendation = {
        'recommended_pathway': recommended_pathway,
        'confidence': round(confidence, 1),
        'alternative_pathway': alternative_pathway,
        'alternative_confidence': round(alternative_confidence, 1),
        'key_factors': top_factors['feature'].tolist(),
        'all_pathway_scores': {
            pathway: round(prob * 100, 1)
            for pathway, prob in zip(pathways, probabilities)
        }
    }

    return recommendation

# Example: Recommend for new referral
new_referral = {
    'risk_level': 3,
    'housing_stable': 1,
    'support_network_strength': 4,
    'previous_service_completion': 1,
    'mental_health_needs': 1,
    'substance_use_needs': 0,
    'employment_needs': 1,
    'crisis_indicators': 0,
    'ready_for_group_work': 1,
    'months_since_last_service': 6
}

recommendation = recommend_pathway(new_referral)

print("\n" + "="*60)
print("Example Recommendation for New Referral:")
print("="*60)
print(f"\nRecommended pathway: {recommendation['recommended_pathway']}")
print(f"Confidence: {recommendation['confidence']}%")
print(f"\nAlternative: {recommendation['alternative_pathway']}")
print(f"Confidence: {recommendation['alternative_confidence']}%")
print(f"\nKey factors driving recommendation:")
for factor in recommendation['key_factors']:
    print(f"  - {factor}")
print(f"\nAll pathway scores:")
for pathway, score in recommendation['all_pathway_scores'].items():
    print(f"  {pathway}: {score}%")

print("\n" + "="*60)
print("IMPORTANT:")
print("- This is a recommendation, NOT a decision")
print("- Professional must review considering full context")
print("- Never route automatically without human oversight")
print("- Model can't see everything (recent changes, cultural factors, etc.)")
print("="*60)

# Save model for use
import pickle
with open('pathway_recommendation_model.pkl', 'wb') as f:
    pickle.dump(rf, f)

print("\nModel saved to pathway_recommendation_model.pkl")
print("\nNext steps:")
print("1. Review model performance with service delivery team")
print("2. Test recommendations against professional judgement")
print("3. Implement with mandatory human oversight")
print("4. Track outcomes and refine monthly")

Tools

Google Colabplatform · freemium
Visit →
scikit-learnlibrary · free · open source
Visit →
pandaslibrary · free · open source
Visit →

Resources

At a glance

Time to implement
weeks
Setup cost
free
Ongoing cost
free
Cost trend
stable
Organisation size
medium, large
Target audience
program-delivery, operations-manager, data-analyst

All tools are free. All processing runs locally - no data sent to external services. GDPR compliant as long as you have lawful basis. Critical: this is a decision support tool, not automated decision-making. Human professionals must review all recommendations. Initial setup takes time (cleaning data, building model). Once built, generating recommendations takes seconds.

Part of this pathway

Written by Make Sense Of It

Last updated: 2024-12-22