We are going to design an ensemble orchestrator that:
- Weights multiple expert models (could be different models or same model with different parameters)
- Captures confidence bounds (e.g., prediction intervals, uncertainty estimates)
- Streams metrics (real-time or batch, but we design for streaming)
We assume the experts are already trained and we have their prediction interfaces.
Steps:
- We need to define an interface for an expert (a model that can predict and possibly provide confidence/uncertainty).
- The orchestrator will maintain a set of experts and their weights (which can be static or dynamically updated).
- For each input, the orchestrator will:
a. Get predictions and confidence bounds from each expert.
b. Combine the predictions using the weights (weighted average, weighted median, etc. - we need to decide).
c. Also, we can compute overall confidence bounds by combining the experts' bounds (e.g., taking the union of intervals, or using weighted variance).
- Stream metrics: we might want to track the performance of each expert and the ensemble over time, and possibly adjust weights.
Let's break down:
Design:
-
Expert interface:
predict(features) -> (prediction, lower_bound, upper_bound) or (prediction, uncertainty)
Note: not all models provide bounds. We might have to estimate from multiple runs or use a model that does.
-
We have two modes for the ensemble:
a. Static weights: fixed by prior knowledge (e.g., validation performance)
b. Dynamic weights: updated based on recent performance (e.g., exponential moving average of error)
-
We'll design the orchestrator to support both.
Implementation:
We'll create:
class Expert:
def init(self, model, name, weight=1.0, dynamic=False, **kwargs):
self.model = model # the actual model object
self.name = name
self.weight = weight # current weight
self.dynamic = dynamic # if dynamic, we will update weight based on performance
# for dynamic, we might keep a history of errors and compute weight as 1 / (error + epsilon) or similar.
class EnsembleOrchestrator:
def init(self, experts, combination_method='weighted_average',
dynamic_weight_update=False, window_size=100):
self.experts = experts # list of Expert objects
self.combination_method = combination_method
self.dynamic_weight_update = dynamic_weight_update
self.window_size = window_size # for rolling window of errors
# For dynamic weights, we might store recent errors for each expert.
# We can use a deque for each expert to store the last window_size errors.
if dynamic_weight_update:
self.errors = {expert.name: deque(maxlen=window_size) for expert in experts}
def predict(self, features, true_label=None):
# If we have true_label, we can compute error and update dynamic weights.
# Otherwise, we just predict.
predictions = []
lower_bounds = []
upper_bounds = []
for expert in self.experts:
pred, lb, ub = expert.predict(features) # assuming the expert returns these three
predictions.append(pred)
lower_bounds.append(lb)
upper_bounds.append(ub)
# Combine predictions and bounds.
if self.combination_method == 'weighted_average':
weights = [expert.weight for expert in self.experts]
total_weight = sum(weights)
normalized_weights = [w/total_weight for w in weights]
# Weighted average of predictions
ensemble_pred = sum(p * w for p, w in zip(predictions, normalized_weights))
# For bounds, we can take weighted average of lower and upper?
# But note: bounds are intervals, so we might want to take the union or a weighted average of the endpoints?
# Alternatively, we can compute the weighted average and then add a bound that covers the spread.
# Let's do:
# ensemble_lb = weighted average of lower_bounds
# ensemble_ub = weighted average of upper_bounds
ensemble_lb = sum(lb * w for lb, w in zip(lower_bounds, normalized_weights))
ensemble_ub = sum(ub * w for ub, w in zip(upper_bounds, normalized_weights))
else:
raise NotImplementedError
# If we have true_label and dynamic weights are enabled, update the weights.
if true_label is not None and self.dynamic_weight_update:
self._update_weights(predictions, true_label)
return ensemble_pred, ensemble_lb, ensemble_ub
def _update_weights(self, predictions, true_label):
# Compute errors for each expert
for expert, pred in zip(self.experts, predictions):
error = self._compute_error(pred, true_label)
self.errors[expert.name].append(error)
# Update weights based on recent errors (e.g., inverse of average error over the window)
for expert in self.experts:
if len(self.errors[expert.name]) > 0:
avg_error = sum(self.errors[expert.name]) / len(self.errors[expert.name])
# Avoid division by zero, and we want higher weight for lower error.
# We can set weight = 1/(avg_error + epsilon) but then we need to renormalize?
# Alternatively, we can use softmax with negative error.
# Let's do: weight = exp(-avg_error) but then we have to normalize.
# We'll do: weight = 1 / (avg_error + 1e-8) and then normalize so that sum of weights is 1.
expert.weight = 1 / (avg_error + 1e-8)
# Normalize weights so they sum to 1? Or keep them as relative?
# Let's normalize so that the weights are in [0,1] and sum to 1.
total_weight = sum(expert.weight for expert in self.experts)
for expert in self.experts:
expert.weight = expert.weight / total_weight
def _compute_error(self, pred, true_label):
# We can use squared error for regression, or 0/1 loss for classification.
# We need to know the task? Let's assume regression for now.
return (pred - true_label) ** 2
def stream_metrics(self, metrics_dict):
# This method is for streaming metrics. We might want to log the current state of the ensemble.
# For example, we can log the current weights, the error of each expert, etc.
# We assume metrics_dict is a dictionary that we can update and then send to a monitoring system.
# We'll just return a dictionary with current metrics.
metrics = {
'weights': {expert.name: expert.weight for expert in self.experts},
'errors': {expert.name: list(self.errors[expert.name]) if self.dynamic_weight_update else None
for expert in self.experts}
}
return metrics
However, note: the above design for dynamic weights uses the error of the expert's prediction on the true label.
But in a real streaming scenario, we might not have the true label immediately. We might have a delay.
Also, we are updating weights after every prediction if we have the true label. This might be too frequent.
We can adjust:
Option 1: Update weights in batches (every N samples) or on a timer.
Option 2: Use an online update (like exponential moving average) for the error.
Let's change the dynamic weight update to use an exponential moving average (EMA) of the error.
Revised dynamic weight update:
For each expert, we keep:
ema_error: exponential moving average of the error.
Then weight = 1 / (ema_error + epsilon)
EMA update:
ema_error = alpha * current_error + (1-alpha) * previous_ema_error
We'll need to initialize the ema_error for each expert.
We can do:
class Expert:
def __init__(self, model, name, weight=1.0, dynamic=False, alpha=0.1, **kwargs):
...
self.dynamic = dynamic
self.alpha = alpha
self.ema_error = None # will be set on first update
Then in _update_weights:
for expert, pred in zip(self.experts, predictions):
error = self._compute_error(pred, true_label)
if expert.ema_error is None:
expert.ema_error = error
else:
expert.ema_error = expert.alpha * error + (1 - expert.alpha) * expert.ema_error
# Then set weight based on ema_error
for expert in self.experts:
expert.weight = 1 / (expert.ema_error + 1e-8)
# Then normalize.
But note: we might want to have a separate ema_error for each expert and update only when we get true label.
However, if we don't get true label for a while, the ema_error will be stale.
Alternatively, we can have a window of recent errors and compute the average, but that uses more memory.
Since we are designing for streaming, let's stick with EMA.
Also, we might want to have a minimum weight (to avoid zero) and maximum weight.
We can adjust:
expert.weight = max(min_weight, min(max_weight, 1/(expert.ema_error+1e-8)))
Then normalize? Or we can just use the raw 1/ema_error and then normalize?
If we normalize, then the weights are relative and sum to 1. But if we set min and max, then after normalization they might not be exactly min and max.
Alternatively, we can use softmax on negative ema_error:
weight = exp(-expert.ema_error / temperature)
But then we don't have to worry about the scale of ema_error.
Let's change:
For dynamic weights, we'll use:
expert.weight = exp(-expert.ema_error / temperature)
Then normalize so that sum of weights is 1.
But note: if ema_error is very large, then exp(-large) is near 0, which is good.
We can set temperature to control how sensitive we are to error.
Alternatively, we can skip the normalization and let the weights be relative?
But then in the weighted average we need normalized weights.
So we do:
weights = [exp(-expert.ema_error / temperature) for expert in self.experts]
total = sum(weights)
normalized_weights = [w/total for w in weights]
And then set expert.weight to the normalized weight? Or keep the raw and normalize in prediction?
We can keep the raw weight (which is not normalized) and then normalize in predict.
But then when we stream metrics, we might want to show the normalized weights.
Let's change the Expert class to store the raw score (which we will use for weight) and then we normalize in predict.
Alternatively, we can store the normalized weight in the expert and update it every time.
Since we update the weight every time we get a true label, we can update the normalized weight then.
But note: the normalization depends on all experts. So we have to update all experts' weights when one expert's ema_error changes.
So in _update_weights:
# First update ema_error for each expert that we have a prediction for.
# Then compute raw_weights = [exp(-expert.ema_error / temperature) for expert in self.experts]
# Then normalize and assign to expert.weight.
But note: what if an expert didn't get a true label in this update? Then we don't update its ema_error, so its weight remains the same?
But then when we normalize, the other experts' weights might change because the total changes.
Alternatively, we can update the weight of only the experts that got a true label? But then the normalization factor changes for all.
We can do:
Step 1: Update ema_error for the experts that have a true label (we have predictions for all, so we have true label for all?
but in streaming, we might get true label for only some?).
Let's assume we get true label for every sample we predict on.
So we update every expert every time.
But if we don't get true label for some, then we skip updating their ema_error? Then we use the old ema_error.
So in _update_weights:
for expert, pred in zip(self.experts, predictions):
error = self._compute_error(pred, true_label)
if expert.ema_error is None:
expert.ema_error = error
else:
expert.ema_error = expert.alpha * error + (1 - expert.alpha) * expert.ema_error
# Now compute weights for all experts from their current ema_error.
raw_weights = [math.exp(-expert.ema_error / temperature) for expert in self.experts]
total = sum(raw_weights)
for expert, raw in zip(self.experts, raw_weights):
expert.weight = raw / total
But note: the temperature parameter: we can set it per expert or globally? We'll set globally for now.
We can make temperature a parameter of the orchestrator.
Alternatively, we can use a different function, but let's stick with this.
5. Confidence bounds:
We are currently taking weighted average of lower bounds and upper bounds.
But note: if the experts have different levels of confidence, we might want to combine the intervals in a way that the ensemble interval covers the true value with a certain probability.
One way:
We have for each expert: [lb_i, ub_i] with some confidence level (say 95%).
We want an ensemble interval that also has 95% coverage.
If the experts are independent, we can combine by taking the union? But that might be too wide.
Alternatively, we can take a weighted average of the endpoints and then adjust the width by the weighted variance of the predictions.
But note: the experts might have different calibration.
Since this is complex, we'll stick with the weighted average of the endpoints for now.
Alternatively, we can compute the ensemble prediction and then use the weighted variance to form an interval:
ensemble_pred = weighted average of predictions
weighted_variance = sum( weight_i * (pred_i - ensemble_pred)**2 for each expert )
Then we can set:
ensemble_lb = ensemble_pred - z * sqrt(weighted_variance)
ensemble_ub = ensemble_pred + z * sqrt(weighted_variance)
But note: the experts already provide bounds. We might want to combine those bounds.
We'll leave it as weighted average of the provided bounds for now.
6. Streaming metrics:
We'll log:
- current weights (normalized)
- current ema_error for each expert
- the ensemble prediction and the true label (if available) to compute ensemble error.
We can also log the individual expert predictions and bounds.
We'll design a method that returns a dictionary of metrics that can be sent to a streaming system (like Kafka, or just print).
We can also have a callback for each prediction to log.
7. We might want to have a way to add or remove experts dynamically.
We can have:
add_expert(expert)
remove_expert(expert_name)
But note: if we are using dynamic weights with EMA, we have to initialize the ema_error for the new expert.
We can set the initial ema_error to a high value (so weight is low) or to the average of current experts? Or we can set it to None and then on first update set it.
Similarly, when removing an expert, we have to renormalize the weights? But we are normalizing every time, so it's okay.
8. We also need to think about the case when an expert fails (e.g., returns NaN). We should handle that.
In predict, if an expert fails, we can set its prediction to None and then in the weighted average skip it? But then we have to adjust weights.
Alternatively, we can set a very low weight for that expert until it recovers.
We can do:
try:
pred, lb, ub = expert.predict(features)
except:
pred, lb, ub = None, None, None
# and then set weight to 0 for this expert? But then we have to renormalize.
But note: if we set weight to 0, then in normalization we have to adjust.
Alternatively, we can remove the expert from the list of experts for this prediction? But then we are changing the set.
We'll do:
In predict, we collect the predictions that are not None.
Then we use only the experts that returned a valid prediction.
But then the weights of the remaining experts might not sum to 1? We have to renormalize the weights of the valid experts.
So:
valid_experts = []
valid_predictions = []
valid_lower_bounds = []
valid_upper_bounds = []
for expert in self.experts:
try:
pred, lb, ub = expert.predict(features)
if pred is None or math.isnan(pred) or lb is None or math.isnan(lb) or ub is None or math.isnan(ub):
raise ValueError("Invalid prediction")
valid_experts.append(expert)
valid_predictions.append(pred)
valid_lower_bounds.append(lb)
valid_upper_bounds.append(ub)
except:
# log the error
pass
Then we use valid_experts and their weights. But note: the weights of the valid_experts are the original weights?
We should renormalize the weights of the valid_experts to sum to 1.
So:
total_weight = sum(expert.weight for expert in valid_experts)
normalized_weights = [expert.weight/total_weight for expert in valid_experts]
Then proceed with valid_experts, valid_predictions, etc.
But note: the expert's weight in the Expert object is not changed. We are just using a normalized version for this prediction.
However, for dynamic weight update, we still update the weight of the expert (even if it failed in this prediction?)
We don't have a prediction from it, so we cannot compute error. So we skip updating the weight for that expert.
In _update_weights, we update only for the experts that we have predictions for? But then we have a mismatch.
We have to be careful: in _update_weights, we are passed the list of predictions (from the valid_experts) and the true_label.
So we update only the experts that were valid.
But then the weights of the invalid experts are not updated. They remain the same.
This is acceptable.
9. We might want to have a way to set the combination method and the temperature for dynamic weights.
We can set these in the constructor.
10. We might also want to have a way to get the current state of the orchestrator (weights, ema_errors) for debugging.
Let's code accordingly.
However, note: the above design is for regression. For classification, we might have probabilities.
We can adjust the expert interface to return:
For regression: (prediction, lb, ub)
For classification: (class_label, prob, lb, ub) or (probabilities, lb, ub) for each class?
But then the combination method for classification is more complex.
We'll stick to regression for simplicity.
11. We'll also assume that the experts are independent and we are combining their point predictions.
For classification, we might want to combine probabilities (by weighted average of probabilities) and then take the class with the highest probability.
We can extend the combination method to support:
- weighted_average (for regression and probability vectors)
- weighted_median (for regression)
- weighted_mode (for classification, but then we need to combine the class labels)
But for now, we do weighted average.
12. We might want to have a way to set the initial weights.
We can set in the Expert constructor.
13. We might want to have a way to reset the dynamic state (ema_error) for an expert.
Given the complexity, we'll code a basic version and then extend.
Let's code:
We'll create:
class Expert:
def __init__(self, model, name, weight=1.0, dynamic=False, alpha=0.1, temperature=1.0):
self.model = model
self.name = name
self.weight = weight # this will be the normalized weight after dynamic updates? Or we store the raw score?
# We'll store the raw score for dynamic, and then we compute the normalized weight in the orchestrator?
# But we want to access the current normalized weight for streaming metrics.
# Let's change: we store the raw_score (which is 1/ema_error or exp(-ema_error/temperature)) and then we compute normalized weight in the orchestrator.
# However, we want to be able to set an initial static weight. So:
if dynamic:
self.raw_score = None # will be computed from ema_error
self.ema_error = None
self.alpha = alpha
self.temperature = temperature
else:
self.raw_score = weight # for static, we use the given weight as raw_score.
# But then in the orchestrator, for static we don't have ema_error, so we use the raw_score.
Then in the orchestrator, when we compute weights for prediction, we do:
if expert.dynamic:
raw = exp(-expert.ema_error / expert.temperature)
else:
raw = expert.raw_score
Then we normalize.
And when we update dynamic weights, we update expert.ema_error and then set expert.raw_score = exp(-expert.ema_error / expert.temperature)
But then we have to store the normalized weight? We can compute it on the fly.
Alternatively, we can store the normalized weight in the expert and update it every time we update the dynamic weights.
Let's do:
For dynamic experts, we store:
ema_error, alpha, temperature, and weight (which is normalized among dynamic and static?).
But note: we have both dynamic and static experts. So when we normalize, we consider all experts (both dynamic and static).
So we can store:
For static: raw_score = weight (and then we don't change it)
For dynamic: raw_score = exp(-ema_error / temperature) (and we update it when we update ema_error)
Then we normalize the raw_score of all experts to get the weight.
So in the expert, we don't store the normalized weight, we store the raw_score.
Then in the orchestrator, we compute the normalized weight for each expert by:
total_raw = sum(expert.raw_score for expert in self.experts)
normalized_weight = expert.raw_score / total_raw
But then we have to update the raw_score for dynamic experts when we get a true label.
And we have to initialize the raw_score for dynamic experts? We can set it to 1.0 initially? But then if we have static experts with weight 1, then they are equal.
Alternatively, we can set the initial raw_score for dynamic experts to 1.0 and then update.
But note: the static expert's raw_score is fixed, so if we set dynamic to 1.0 initially, then they are equal.
We can do:
In Expert.__init__:
if dynamic:
self.raw_score = 1.0 # initial raw score
self.ema_error = None
else:
self.raw_score = weight
Then in _update_weights, we update the ema_error and then set raw_score = exp(-ema_error/temperature)
Then we don't need to store the normalized weight in the expert.
But then when we stream metrics, we might want to show the normalized weight? We can compute it on the fly.
However, we also want to show the raw_score (which for dynamic is exp(-ema_error/temperature) and for static is the given weight).
So we can compute the normalized weight in the stream_metrics method by:
total_raw = sum(expert.raw_score for expert in self.experts)
normalized_weights = {expert.name: expert.raw_score/total_raw for expert in self.experts}
And then return that.
But note: if an expert is invalid in the current prediction, we don't include it in the prediction, but we still include it in the metrics?
We might want to show the weight of the expert even if it failed? Yes, because the weight is a property of the expert, not of the current prediction.
So in stream_metrics, we use all experts.
However, in the predict method, when we have invalid experts, we use only the valid ones and renormalize the raw_scores of the valid experts?
Wait, no: the raw_score is a property of the expert and doesn't change because of invalidity. But when we combine, we only use the valid experts and we have to renormalize the raw_scores of the valid ones.
So in predict:
valid_experts = [expert for expert in self.experts if expert is valid]
Then we compute the total_raw among valid_experts:
total_raw = sum(expert.raw_score for expert in valid_experts)
Then for each valid_expert, normalized_weight = expert.raw_score / total_raw.
So the raw_score is not normalized, and we normalize only when we have a set of valid experts.
This means that the normalized weight of an expert can change from one prediction to the next if some experts are invalid.
But that's acceptable because if an expert is invalid, we don't want to use it.
However, note: the raw_score of an expert is not changed by invalidity. So if an expert is invalid, its raw_score remains the same, but in the next prediction when it is valid, it will have the same raw_score and then be normalized with the other valid experts.
This is acceptable.
But then in the dynamic weight update, we update the raw_score of the expert (by updating ema_error and then raw_score = exp(-ema_error/temperature)) regardless of whether it was valid in the current prediction?
We update the ema_error only if we have a prediction from that expert (i.e., it was valid). So if it was invalid, we don't update its ema_error and hence its raw_score remains the same.
This is consistent.
So let's adjust:
In predict, we get a list of valid_experts and their predictions.
Then we compute the weighted average using the raw_scores of the valid_experts, normalized by the total raw_score of valid_experts.
Then, if we have true_label, we update the ema_error for each expert that was valid (i.e., that we have a prediction for) and then update its raw_score.
Note: we don't update the ema_error for invalid experts.
So the code for predict:
valid_experts = []
valid_predictions = []
valid_lower_bounds = []
valid_upper_bounds = []
for expert in self.experts:
try:
pred, lb, ub = expert.predict(features)
if pred is None or math.isnan(pred) or lb is None or math.isnan(lb) or ub is None or math.isnan(ub):
raise ValueError("Invalid prediction")
valid_experts.append(expert)
valid_predictions.append(pred)
valid_lower_bounds.append(lb)
valid_upper_bounds.append(ub)
except Exception as e:
# log the exception
pass
if len(valid_experts) == 0:
# no valid expert, return None or raise?
return None, None, None
# Compute total raw_score for valid experts
total_raw = sum(expert.raw_score for expert in valid_experts)
normalized_weights = [expert.raw_score / total_raw for expert in valid_experts]
# Combine
ensemble_pred = sum(p * w for p, w in zip(valid_predictions, normalized_weights))
ensemble_lb = sum(lb * w for lb, w in zip(valid_lower_bounds, normalized_weights))
ensemble_ub = sum(ub * w for ub, w in zip(valid_upper_bounds, normalized_weights))
# If we have true_label, update the ema_error for valid experts and then their raw_score.
if true_label is not None and self.dynamic_weight_update:
for expert, pred in zip(valid_experts, valid_predictions):
error = self._compute_error(pred, true_label)
if expert.ema_error is None:
expert.ema_error = error
else:
expert.ema_error = expert.alpha * error + (1 - expert.alpha) * expert.ema_error
# Update raw_score from ema_error
expert.raw_score = math.exp(-expert.ema_error / expert.temperature)
return ensemble_pred, ensemble_lb, ensemble_ub
Then in stream_metrics, we can compute the normalized weights over all experts (even if some are invalid in the current prediction, we use all experts because we want to see the overall weight distribution).
But note: the raw_score of an expert might be very low (if it has high ema_error) but then in the next prediction if it is invalid, it doesn't get updated and its raw_score remains low.
This is acceptable.
14. We also need to handle the case when the orchestrator is initialized with dynamic=False for all experts.
Then we never update the raw_score.
And we never update the ema_error.
15. We might want to have a way to set the raw_score for static experts? We already set in the constructor.
-
We might want to have a way to reset the ema_error for a dynamic expert (e.g., when we want to forget the past).
We can have a method:
reset_expert(expert_name)
that sets expert.ema_error = None and expert.raw_score = 1.0 (or the initial value?).
But then we have to decide the initial raw_score for dynamic experts. We set to 1.0.
-
We might want to have a way to change the alpha or temperature for a dynamic expert.
We can set them in the expert object.
Given the complexity, let's code the basic version and then we can extend.
Let's code the classes:
We assume the expert model has a predict method that returns (pred, lb, ub). If the model doesn't provide lb and ub, we can set them to None? But then we cannot use them for bounds.
We can have a flag in the expert to indicate if it provides bounds.
Alternatively, we can have the expert return a dictionary with more information.
But for simplicity, we assume the expert returns (pred, lb, ub). If the expert doesn't have bounds, we can set lb = pred and ub = pred? Then the ensemble bounds will be the same as the weighted average of the point predictions.
But that's not useful.
Alternatively, we can have the expert return a confidence interval or a standard deviation.
We'll assume the expert returns a tuple (pred, lower, upper) for a given confidence level (say 95%).
If the expert doesn't provide bounds, we can have the orchestrator skip the bounds? But then we cannot compute ensemble bounds.
We can have:
If any expert doesn't provide bounds, then we don't compute ensemble bounds? Or we set the ensemble bounds to the weighted average of the predictions (so a point estimate).
We'll do:
In the expert, if the model doesn't provide bounds, we set lb = pred and ub = pred.
Then the ensemble bounds will be the same as the ensemble prediction? Not exactly, because we take weighted average of lb and ub.
If all experts set lb=pred and ub=pred, then ensemble_lb = ensemble_ub = ensemble_pred.
So we get a point estimate.
But if some experts have bounds and some don't, then we are mixing.
We might want to only use the bounds from experts that provide bounds? But then how to combine?
Alternatively, we can have a separate method for bounds that only uses experts that provide bounds.
Given the complexity, we'll assume all experts provide bounds.
18. We'll also assume that the experts are for regression and the bounds are for the same confidence level.
- We'll code accordingly.
Let's code the classes:
Note: We are going to use math.exp, so we need to import math.
We'll also handle the case when the expert's predict returns a tuple of length 3.
If the expert returns only one value (the prediction), then we set lb and ub to that value.
We can adjust the expert interface to be flexible.
Let's change the Expert class to wrap the model and have a predict method that returns (pred, lb, ub).
class Expert:
def __init__(self, model, name, weight=1.0, dynamic=False, alpha=0.1, temperature=1.0, provides_bounds=True):
self.model = model
self.name = name
self.provides_bounds = provides_bounds
if dynamic:
self.raw_score = 1.0
self.ema_error = None
self.alpha = alpha
self.temperature = temperature
else:
self.raw_score = weight
def predict(self, features):
# Call the model's predict method. We assume the model returns either:
# (pred,) or (pred, lb, ub) or (pred, lb, ub, ...)
# We'll adapt.
result = self.model.predict(features)
if isinstance(result, tuple):
pred = result[0]
if self.provides_bounds and len(result) >= 3:
lb = result[1]
ub = result[2]
else:
lb = pred
ub = pred
else:
pred = result
lb = pred
ub = pred
return pred, lb, ub
Then in the orchestrator, we don't need to check the length.
20. We'll also adjust the error computation: we use the prediction (point estimate) to compute error.
-
Let's code the orchestrator accordingly.
-
We'll also add a method to get the current state (for debugging):
def get_state(self):
state = {}
for expert in self.experts:
state[expert.name] = {
'raw_score': expert.raw_score,
'ema_error': expert.ema_error,
'weight': expert.raw_score / sum(e.raw_score for e in self.experts) # normalized weight over all experts
}
return state
-
But note: the normalized weight in get_state is over all experts, but in prediction we use only valid experts.
So the weight we see in get_state might be different from the weight used in the last prediction if some experts were invalid.
We can also store the last normalized weights used in prediction? But that might be too much.
Alternatively, we can have a method that returns the current normalized weights (over all experts) and then in the predict we renormalize only for valid.
We'll leave it as is.
-
We might want to have a way to set the raw_score of an expert (for static experts, we set in constructor; for dynamic, we set via ema_error).
We can have a method:
set_expert_raw_score(expert_name, raw_score)
But then we break the dynamic update? Because the dynamic update will overwrite.
We can only allow setting for static experts? Or we can set the ema_error for dynamic experts?
We'll not implement set_expert_raw_score for now.
-
We might want to have a way to change the alpha and temperature for a dynamic expert.
We can have:
set_expert_params(expert_name, alpha=None, temperature=None)
Then update the expert's parameters.
But note: changing the temperature will change the raw_score immediately? We can recompute.
We can do:
if alpha is not None:
expert.alpha = alpha
if temperature is not None:
expert.temperature = temperature
# then if expert.ema_error is not None, update raw_score
if expert.ema_error is not None:
expert.raw_score = math.exp(-expert.ema_error / expert.temperature)
But then we have to renorm? The raw_score change will affect the normalization.
We don't need to renorm because the raw_score is used in the next normalization.
So it's okay.
-
We'll code accordingly.
Given the complexity, we'll write the code for the orchestrator and the expert.
Let's code:
We assume the model has a predict method that returns a tuple or a single value.
We'll handle the bounds in the expert's predict.
We'll also assume that the orchestrator is for regression.
We'll leave classification for future extension.
Let's code the classes.
Note: We are going to use deque for the window? But we are using EMA, so we don't need deque.
We are using EMA, so we don't need to store a window of errors.
Let's code accordingly.
I'll design a comprehensive Model Ensemble Orchestrator that dynamically weights expert models, captures confidence bounds, and streams metrics in real-time. This system is suitable for production ML deployments requiring robustness and transparency.
Core Architecture
"""
Model Ensemble Orchestrator
Dynamic expert weighting with confidence bounds and streaming metrics
"""
import heapq
import time
import uuid
from abc import ABC, abstractmethod
from collections import deque
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from scipy import stats
class WeightStrategy(Enum):
"""Strategies for computing ensemble weights"""
FIXED = "fixed" # Static weights
PERFORMANCE = "performance" # Based on recent accuracy
UNCERTAINTY = "uncertainty" # Inverse of prediction uncertainty
ADAPTIVE = "adaptive" # Combines multiple signals
BANDIT = "bandit" # Multi-armed bandit approach
class MetricType(Enum):
"""Types of metrics to stream"""
ACCURACY = "accuracy"
LATENCY = "latency"
THROUGHPUT = "throughput"
CONFIDENCE = "confidence"
DRIFT = "drift"
WEIGHTS = "weights"
COVERAGE = "coverage"
@dataclass
class PredictionResult:
"""Container for model prediction with metadata"""
model_id: str
value: Union[float, np.ndarray, List]
confidence_low: float
confidence_high: float
uncertainty: float
latency_ms: float
timestamp: float = field(default_factory=time.time)
metadata: Dict[str, Any] = field(default_factory=dict)
@dataclass
class EnsembleMetrics:
"""Streaming metrics container"""
timestamp: float
ensemble_prediction: Any
confidence_interval: Tuple[float, float]
weights: Dict[str, float]
individual_metrics: Dict[str, Dict[str, float]]
system_metrics: Dict[str, float]
drift_score: Optional[float] = None
class ExpertModel(ABC):
"""Abstract base class for expert models"""
def __init__(self, model_id: str, model: Any):
self.model_id = model_id
self.model = model
self._prediction_history = deque(maxlen=1000)
self._error_history = deque(maxlen=1000)
self._last_update = time.time()
@abstractmethod
def predict(self, X: Any) -> PredictionResult:
"""Make prediction with confidence bounds"""
pass
@abstractmethod
def get_uncertainty(self, X: Any) -> float:
"""Estimate prediction uncertainty"""
pass
def update_performance(self, y_true: Any, y_pred: Any):
"""Update model performance metrics"""
error = self._calculate_error(y_true, y_pred)
self._error_history.append(error)
self._last_update = time.time()
def get_recent_performance(self, window: int = 100) -> float:
"""Get recent accuracy metric (lower is better)"""
if not self._error_history:
return 1.0 # Default high error
recent_errors = list(self._error_history)[-window:]
return np.mean(recent_errors) if recent_errors else 1.0
def _calculate_error(self, y_true: Any, y_pred: Any) -> float:
"""Calculate prediction error (to be implemented by subclasses)"""
return float(np.abs(y_true - y_pred))
class EnsembleOrchestrator:
"""
Dynamic ensemble orchestrator with:
- Adaptive weighting based on performance/uncertainty
- Confidence interval aggregation
- Real-time metrics streaming
- Drift detection
"""
def __init__(
self,
experts: List[ExpertModel],
weight_strategy: WeightStrategy = WeightStrategy.ADAPTIVE,
min_weight: float = 0.01,
confidence_level: float = 0.95,
metrics_window: int = 1000,
drift_detection_window: int = 100,
update_interval: float = 1.0
):
"""
Initialize orchestrator
Args:
experts: List of expert models
weight_strategy: Strategy for computing weights
min_weight: Minimum weight for any expert
confidence_level: Confidence level for intervals (0-1)
metrics_window: Window size for metrics
drift_detection_window: Window for drift detection
update_interval: Seconds between weight updates
"""
self.experts = {expert.model_id: expert for expert in experts}
self.weight_strategy = weight_strategy
self.min_weight = min_weight
self.confidence_level = confidence_level
# State
self._weights = self._initialize_weights()
self._prediction_history = deque(maxlen=metrics_window)
self._metrics_buffer = deque(maxlen=metrics_window)
self._drift_scores = deque(maxlen=drift_detection_window)
self._last_weight_update = time.time()
self.update_interval = update_interval
# Callbacks
self._metric_callbacks: List[Callable[[EnsembleMetrics], None]] = []
self._drift_callbacks: List[Callable[[float], None]] = []
# Performance tracking
self._ensemble_errors = deque(maxlen=metrics_window)
self._coverage_counts = deque(maxlen=metrics_window)
def _initialize_weights(self) -> Dict[str, float]:
"""Initialize weights uniformly"""
n = len(self.experts)
return {model_id: 1.0/n for model_id in self.experts.keys()}
def predict(
self,
X: Any,
true_y: Optional[Any] = None,
update_weights: bool = True
) -> PredictionResult:
"""
Make ensemble prediction with confidence bounds
Args:
X: Input features
true_y: Optional true value for weight updates
update_weights: Whether to update weights based on strategy
Returns:
PredictionResult with ensemble prediction and metadata
"""
start_time = time.time()
# Get predictions from all experts
predictions = {}
for model_id, expert in self.experts.items():
try:
pred = expert.predict(X)
predictions[model_id] = pred
except Exception as e:
predictions[model_id] = None
# Log error but continue
# Filter valid predictions
valid_predictions = {
mid: p for mid, p in predictions.items()
if p is not None
}
if not valid_predictions:
raise ValueError("All experts failed to predict")
# Update weights if needed
if update_weights and true_y is not None:
self._update_weights(valid_predictions, true_y)
# Combine predictions
ensemble_value, ensemble_bounds = self._aggregate_predictions(valid_predictions)
# Calculate ensemble metrics
latency = (time.time() - start_time) * 1000
ensemble_uncertainty = self._calculate_ensemble_uncertainty(valid_predictions)
# Create result
result = PredictionResult(
model_id="ensemble",
value=ensemble_value,
confidence_low=ensemble_bounds[0],
confidence_high=ensemble_bounds[1],
uncertainty=ensemble_uncertainty,
latency_ms=latency,
metadata={
"expert_predictions": {
mid: {
"value": p.value,
"uncertainty": p.uncertainty,
"latency": p.latency_ms
} for mid, p in valid_predictions.items()
},
"weights": self._weights.copy()
}
)
# Store and stream metrics
self._store_prediction(result, true_y)
self._stream_metrics(result, valid_predictions)
# Check for drift
if len(self._prediction_history) >= 100:
self._detect_drift()
return result
def _aggregate_predictions(
self,
predictions: Dict[str, PredictionResult]
) -> Tuple[float, Tuple[float, float]]:
"""
Aggregate predictions using weighted combination
Returns: (ensemble_value, (lower_bound, upper_bound))
"""
# Weighted average of point predictions
total_weight = sum(self._weights[mid] for mid in predictions.keys())
normalized_weights = {
mid: self._weights[mid] / total_weight
for mid in predictions.keys()
}
ensemble_value = sum(
pred.value * normalized_weights[mid]
for mid, pred in predictions.items()
)
# Combine confidence intervals
# Assuming normal distribution of errors, combine variances
weighted_variance = 0.0
for mid, pred in predictions.items():
# Convert confidence interval to standard deviation
ci_width = pred.confidence_high - pred.confidence_low
z = stats.norm.ppf((1 + self.confidence_level) / 2)
std = ci_width / (2 * z) if z > 0 else pred.uncertainty
# Weighted average of variances
weighted_variance += (normalized_weights[mid] ** 2) * (std ** 2)
ensemble_std = np.sqrt(weighted_variance)
z = stats.norm.ppf((1 + self.confidence_level) / 2)
margin = z * ensemble_std
return ensemble_value, (
ensemble_value - margin,
ensemble_value + margin
)
def _update_weights(self, predictions: Dict[str, PredictionResult], true_y: Any):
"""Update expert weights based on strategy"""
current_time = time.time()
# Only update at specified intervals
if current_time - self._last_weight_update < self.update_interval:
return
if self.weight_strategy == WeightStrategy.FIXED:
return
# Calculate performance scores (lower is better)
performance_scores = {}
for mid, pred in predictions.items():
error = abs(pred.value - true_y)
performance_scores[mid] = error
# Update weights based on strategy
new_weights = {}
if self.weight_strategy == WeightStrategy.PERFORMANCE:
# Inverse of error (with smoothing)
for mid, score in performance_scores.items():
new_weights[mid] = 1.0 / (score + 1e-8)
elif self.weight_strategy == WeightStrategy.UNCERTAINTY:
# Inverse of uncertainty
for mid, pred in predictions.items():
new_weights[mid] = 1.0 / (pred.uncertainty + 1e-8)
elif self.weight_strategy == WeightStrategy.ADAPTIVE:
# Combine performance and uncertainty
for mid, pred in predictions.items():
perf_score = performance_scores[mid]
uncertainty_score = pred.uncertainty
# Weighted combination (tunable)
combined = 0.7 * perf_score + 0.3 * uncertainty_score
new_weights[mid] = 1.0 / (combined + 1e-8)
elif self.weight_strategy == WeightStrategy.BANDIT:
# Simplified bandit algorithm (Thompson sampling-like)
# Using Gaussian priors on performance
for mid in self.experts.keys():
if mid in performance_scores:
# Update posterior (simplified)
error = performance_scores[mid]
# Exponential weighting
new_weights[mid] = np.exp(-error / 0.1)
else:
# Maintain previous weight for missing experts
new_weights[mid] = self._weights[mid] * 0.9
# Normalize and apply minimum weight
total = sum(new_weights.values())
if total > 0:
for mid in new_weights:
new_weights[mid] = max(self.min_weight, new_weights[mid] / total)
# Smooth update (exponential moving average)
alpha = 0.1 # Smoothing factor
for mid in self._weights:
if mid in new_weights:
self._weights[mid] = (
alpha * new_weights[mid] +
(1 - alpha) * self._weights[mid]
)
# Renormalize after smoothing
total = sum(self._weights.values())
for mid in self._weights:
self._weights[mid] /= total
self._last_weight_update = current_time
def _store_prediction(self, result: PredictionResult, true_y: Optional[Any]):
"""Store prediction for drift detection and performance tracking"""
self._prediction_history.append({
'prediction': result.value,
'true': true_y,
'timestamp': result.timestamp,
'weights': result.metadata['weights'].copy()
})
if true_y is not None:
error = abs(result.value - true_y)
self._ensemble_errors.append(error)
# Check coverage
in_bounds = (
true_y >= result.confidence_low and
true_y <= result.confidence_high
)
self._coverage_counts.append(1.0 if in_bounds else 0.0)
def _calculate_ensemble_uncertainty(self, predictions: Dict[str, PredictionResult]) -> float:
"""Calculate combined uncertainty across experts"""
if len(predictions) == 1:
return list(predictions.values())[0].uncertainty
# Disagreement-based uncertainty (variance of predictions)
values = [p.value for p in predictions.values()]
return np.var(values) if len(values) > 1 else 0.0
def _stream_metrics(self, result: PredictionResult, predictions: Dict[str, PredictionResult]):
"""Create and stream ensemble metrics"""
# Individual expert metrics
individual_metrics = {}
for mid, pred in predictions.items():
individual_metrics[mid] = {
'value': float(pred.value),
'uncertainty': float(pred.uncertainty),
'latency_ms': pred.latency_ms,
'confidence_width': float(pred.confidence_high - pred.confidence_low)
}
# System metrics
system_metrics = {
'num_experts': len(predictions),
'active_experts': len(self.experts),
'total_latency_ms': result.latency_ms,
'weight_entropy': -sum(
w * np.log(w + 1e-10)
for w in self._weights.values()
)
}
# Coverage rate
coverage_rate = (
np.mean(list(self._coverage_counts)[-100:])
if self._coverage_counts else 0.0
)
metrics = EnsembleMetrics(
timestamp=time.time(),
ensemble_prediction=result.value,
confidence_interval=(result.confidence_low, result.confidence_high),
weights=self._weights.copy(),
individual_metrics=individual_metrics,
system_metrics={**system_metrics, 'coverage_rate': coverage_rate},
drift_score=self._drift_scores[-1] if self._drift_scores else None
)
self._metrics_buffer.append(metrics)
# Call callbacks
for callback in self._metric_callbacks:
try:
callback(metrics)
except Exception as e:
print(f"Metric callback error: {e}")
def _detect_drift(self):
"""Detect concept drift using prediction errors"""
if len(self._ensemble_errors) < 50:
return
recent_errors = list(self._ensemble_errors)[-50:]
earlier_errors = list(self._ensemble_errors)[-100:-50]
if len(earlier_errors) == 0:
return
# Simple drift detection: significant increase in error
recent_mean = np.mean(recent_errors)
earlier_mean = np.mean(earlier_errors)
# Use Mann-Whitney U test for non-parametric comparison
try:
stat, p_value = stats.mannwhitneyu(
recent_errors,
earlier_errors,
alternative='greater'
)
drift_score = 1.0 - p_value # Higher = more drift
self._drift_scores.append(drift_score)
# Trigger callbacks if drift detected
if p_value < 0.05: # Statistically significant
for callback in self._drift_callbacks:
try:
callback(drift_score)
except Exception as e:
print(f"Drift callback error: {e}")
except Exception:
# Fallback to simple comparison
drift_score = max(0, (recent_mean - earlier_mean) / (earlier_mean + 1e-8))
self._drift_scores.append(drift_score)
def add_metric_callback(self, callback: Callable[[EnsembleMetrics], None]):
"""Register callback for streaming metrics"""
self._metric_callbacks.append(callback)
def add_drift_callback(self, callback: Callable[[float], None]):
"""Register callback for drift detection"""
self._drift_callbacks.append(callback)
def get_recent_metrics(self, n: int = 10) -> List[EnsembleMetrics]:
"""Get recent metrics"""
return list(self._metrics_buffer)[-n:]
def get_current_weights(self) -> Dict[str, float]:
"""Get current expert weights"""
return self._weights.copy()
def add_expert(self, expert: ExpertModel, initial_weight: float = 0.1):
"""Add new expert to ensemble"""
self.experts[expert.model_id] = expert
self._weights[expert.model_id] = initial_weight
# Renormalize weights
total = sum(self._weights.values())
for mid in self._weights:
self._weights[mid] /= total
def remove_expert(self, model_id: str):
"""Remove expert from ensemble"""
if model_id in self.experts:
del self.experts[model_id]
del self._weights[model_id]
# Renormalize
total = sum(self._weights.values())
for mid in self._weights:
self._weights[mid] /= total
def force_weight_update(self):
"""Force immediate weight recalculation"""
self._last_weight_update = 0
def get_coverage_rate(self, window: int = 100) -> float:
"""Get recent coverage rate"""
recent = list(self._coverage_counts)[-window:]
return np.mean(recent) if recent else 0.0
def get_performance_summary(self) -> Dict[str, Any]:
"""Get ensemble performance summary"""
if not self._ensemble_errors:
return {}
errors = list(self._ensemble_errors)
return {
'mean_error': np.mean(errors),
'std_error': np.std(errors),
'max_error': np.max(errors),
'min_error': np.min(errors),
'coverage_rate': self.get_coverage_rate(),
'drift_score': self._drift_scores[-1] if self._drift_scores else 0.0,
'weight_entropy': -sum(
w * np.log(w + 1e-10)
for w in self._weights.values()
),
'num_experts': len(self.experts),
'weight_distribution': self._weights.copy()
}
Example Usage
"""
Example implementation with sklearn models
"""
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.linear_model import LinearRegression
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
class SklearnExpert(ExpertModel):
"""Expert wrapper for sklearn models"""
def __init__(self, model_id: str, model: Any, provides_confidence: bool = False):
super().__init__(model_id, model)
self.provides_confidence = provides_confidence
def predict(self, X: Any) -> PredictionResult:
start = time.time()
# Get predictions
if hasattr(self.model, 'predict_proba'):
probs = self.model.predict_proba(X)
pred = np.argmax(probs, axis=1)
confidence = np.max(probs, axis=1)
else:
pred = self.model.predict(X)
confidence = np.ones_like(pred) * 0.5 # Default
# Get uncertainty (using standard deviation of ensemble if available)
uncertainty = self.get_uncertainty(X)
# Calculate confidence bounds (simplified)
z = 1.96 # 95% confidence
ci_low = pred - z * uncertainty
ci_high = pred + z * uncertainty
latency = (time.time() - start) * 1000
return PredictionResult(
model_id=self.model_id,
value=pred[0] if isinstance(pred, np.ndarray) else float(pred),
confidence_low=float(ci_low[0]) if isinstance(ci_low, np.ndarray) else float(ci_low),
confidence_high=float(ci_high[0]) if isinstance(ci_high, np.ndarray) else float(ci_high),
uncertainty=float(uncertainty[0]) if isinstance(uncertainty, np.ndarray) else float(uncertainty),
latency_ms=latency
)
def get_uncertainty(self, X: Any) -> np.ndarray:
"""Estimate uncertainty"""
if hasattr(self.model, 'estimators_') and len(self.model.estimators_) > 1:
# Use ensemble variance for random forest/gradient boosting
predictions = np.array([
estimator.predict(X)
for estimator in self.model.estimators_
])
return np.std(predictions, axis=0)
else:
# Simple heuristic for single models
return np.ones(len(X)) * 0.1
# Example setup
def create_ensemble():
# Create base models
models = [
RandomForestRegressor(n_estimators=100, random_state=42),
GradientBoostingRegressor(random_state=42),
LinearRegression()
]
# Wrap as experts
experts = [
SklearnExpert(f"rf_{i}", model)
for i, model in enumerate(models[:2])
]
experts.append(SklearnExpert("linear", models[2]))
# Create orchestrator
orchestrator = EnsembleOrchestrator(
experts=experts,
weight_strategy=WeightStrategy.ADAPTIVE,
confidence_level=0.95,
metrics_window=1000
)
# Add metric callback
def log_metrics(metrics: EnsembleMetrics):
print(f"[{metrics.timestamp:.2f}] "
f"Prediction: {metrics.ensemble_prediction:.3f} "
f"CI: [{metrics.confidence_interval[0]:.3f}, {metrics.confidence_interval[1]:.3f}] "
f"Coverage: {metrics.system_metrics.get('coverage_rate', 0):.1%}")
orchestrator.add_metric_callback(log_metrics)
# Add drift callback
def on_drift(drift_score: float):
print(f"⚠️ Drift detected! Score: {drift_score:.3f}")
# Could trigger retraining here
orchestrator.add_drift_callback(on_drift)
return orchestrator
# Usage example
if __name__ == "__main__":
# Generate synthetic data
X, y = make_regression(n_samples=1000, n_features=20, noise=0.1, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Train experts
orchestrator = create_ensemble()
for expert in orchestrator.experts.values():
expert.model.fit(X_train, y_train)
# Make predictions
for i in range(10):
X_sample = X_test[i:i+1]
y_true = y_test[i]
result = orchestrator.predict(X_sample, true_y=y_true)
print(f"Sample {i}: True={y_true:.3f}, "
f"Ensemble={result.value:.3f}, "
f"CI=[{result.confidence_low:.3f}, {result.confidence_high:.3f}]")
# Get current weights
if i % 3 == 0:
weights = orchestrator.get_current_weights()
print(f"Current weights: {weights}")
# Get performance summary
summary = orchestrator.get_performance_summary()
print("\nPerformance Summary:")
for key, value in summary.items():
print(f" {key}: {value}")
Key Features
1. Dynamic Weighting Strategies
- Fixed: Static weights
- Performance: Inverse of recent error
- Uncertainty: Inverse of prediction uncertainty
- Adaptive: Combined performance + uncertainty
- Bandit: Thompson sampling-like approach
2. Confidence Bound Aggregation
- Combines individual confidence intervals
- Uses variance propagation for normal distributions
- Adjusts for ensemble size and weights
3. Real-Time Metrics Streaming
- System metrics: Latency, throughput, weight entropy
- Model metrics: Individual expert performance
- Ensemble metrics: Coverage rate, drift detection
- Callback system: Push metrics to monitoring (Prometheus, Kafka, etc.)
4. Drift Detection
- Mann-Whitney U test on recent errors
- Statistical significance testing
- Configurable sensitivity
5. Operational Features
- Hot-swapping: Add/remove experts at runtime
- Graceful degradation: Skip failed experts
- Smooth updates: EMA-based weight transitions
- Comprehensive logging: Full prediction traceability
Deployment Considerations
"""
Production deployment patterns
"""
class ProductionEnsemble(EnsembleOrchestrator):
"""Production-ready ensemble with additional features"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._circuit_breakers = {}
self._retry_counts = {}
def predict_with_circuit_breaker(
self,
X: Any,
true_y: Optional[Any] = None,
failure_threshold: int = 3,
reset_timeout: float = 60.0
) -> PredictionResult:
"""Predict with circuit breaker pattern for fault tolerance"""
# Check circuit breakers
for mid, expert in self.experts.items():
if mid in self._circuit_breakers:
cb = self._circuit_breakers[mid]
if cb['state'] == 'OPEN':
if time.time() - cb['last_failure'] > reset_timeout:
cb['state'] = 'HALF_OPEN'
else:
# Skip this expert
continue
try:
result = self.predict(X, true_y)
# Reset circuit breaker on success
for mid in self._retry_counts:
if mid in self._circuit_breakers:
self._circuit_breakers[mid]['state'] = 'CLOSED'
self._retry_counts[mid] = 0
return result
except Exception as e:
# Record failure
for mid in self.experts.keys():
if mid not in self._retry_counts:
self._retry_counts[mid] = 0
self._retry_counts[mid] += 1
if self._retry_counts[mid] >= failure_threshold:
self._circuit_breakers[mid] = {
'state': 'OPEN',
'last_failure': time.time()
}
raise
def export_state(self) -> Dict:
"""Export orchestrator state for recovery"""
return {
'weights': self._weights,
'drift_scores': list(self._drift_scores),
'expert_states': {
mid: {
'error_history': list(expert._error_history),
'last_update': expert._last_update
} for mid, expert in self.experts.items()
}
}
def import_state(self, state: Dict):
"""Import orchestrator state"""
self._weights = state['weights']
self._drift_scores = deque(state['drift_scores'], maxlen=100)
for mid, expert_state in state['expert_states'].items():
if mid in self.experts:
expert = self.experts[mid]
expert._error_history = deque(
expert_state['error_history'],
maxlen=1000
)
expert._last_update = expert_state['last_update']
Scaling Considerations
For high-throughput scenarios:
import asyncio
from concurrent.futures import ThreadPoolExecutor
class AsyncEnsembleOrchestrator(EnsembleOrchestrator):
"""Async version for concurrent predictions"""
def __init__(self, *args, max_workers: int = 10, **kwargs):
super().__init__(*args, **kwargs)
self.executor = ThreadPoolExecutor(max_workers=max_workers)
async def predict_async(self, X: Any, true_y: Optional[Any] = None) -> PredictionResult:
"""Async prediction with parallel expert inference"""
loop = asyncio.get_event_loop()
# Parallel predictions
tasks = []
for expert in self.experts.values():
task = loop.run_in_executor(
self.executor,
expert.predict,
X
)
tasks.append(task)
predictions = await asyncio.gather(*tasks, return_exceptions=True)
# Process results (similar to sync version)
valid_predictions = {}
for (mid, _), pred in zip(self.experts.items(), predictions):
if not isinstance(pred, Exception):
valid_predictions[mid] = pred
# ... rest of aggregation logic ...
Monitoring & Visualization
"""
Streaming metrics to Prometheus/Grafana
"""
from prometheus_client import Gauge, Counter, Histogram
class PrometheusMetrics:
"""Prometheus metrics exporter"""
def __init__(self, orchestrator: EnsembleOrchestrator, prefix: str = "ensemble"):
self.orchestrator = orchestrator
# Metrics
self.prediction_counter = Counter(
f'{prefix}_predictions_total',
'Total predictions'
)
self.error_gauge = Gauge(
f'{prefix}_error',
'Current ensemble error'
)
self.latency_histogram = Histogram(
f'{prefix}_latency_seconds',
'Prediction latency'
)
self.weight_gauge = {}
self.coverage_gauge = Gauge(
f'{prefix}_coverage_rate',
'Confidence interval coverage'
)
# Register callback
orchestrator.add_metric_callback(self._update_metrics)
def _update_metrics(self, metrics: EnsembleMetrics):
"""Update Prometheus metrics"""
self.prediction_counter.inc()
self.latency_histogram.observe(metrics.system_metrics['total_latency_ms'] / 1000)
self.coverage_gauge.set(metrics.system_metrics['coverage_rate'])
# Update weight gauges
for mid, weight in metrics.weights.items():
if mid not in self.weight_gauge:
self.weight_gauge[mid] = Gauge(
f'{prefix}_weight',
f'Weight for expert {mid}',
['expert']
)
self.weight_gauge[mid].labels(expert=mid).set(weight)
Best Practices
- Weight Initialization: Start with equal weights or based on offline validation
- Update Frequency: Balance responsiveness vs. stability (1-10 seconds typical)
- Drift Threshold: Tune based on acceptable false positive rate
- Fallback Strategy: Have a default model when ensemble fails
- A/B Testing: Run multiple orchestrators with different strategies
- Resource Limits: Set max latency budgets and timeouts
- Cold Start: Warm-up period with fixed weights until sufficient data
This orchestrator provides a production-ready foundation for dynamic ensemble systems with built-in robustness, monitoring, and adaptability. The modular design allows customization for specific use cases while maintaining core functionality.