Single Predicted Value From Two Models

Version 31 | Created: 2026-09-11 | Updated: 2026-11-07 13:46 UTC
- 1. Purpose
- 2. Summary
- 3. Principle
- 4. Optimal Weight Search
- 5. Cautions
- 6. Further Work
- References
- Appendix A. Terminology
- Appendix B. Python Implementation
- Problem Statement: No simple way to combine the predictions computed by several models into one.
- Goal: A single prediction that accounts for both probabilities, where two models each emit a prediction and a probability.
- Non-Goal: Fitting and improving the models themselves.
The single prediction comes from the two probabilities: y_pred is read off their weighted average, and a predicted value of any other kind is the two values averaged with those same probabilities as weights. Where both models T and S provide predicted probabilities (
A weight w (
The prediction y_pred of a binary classification is decided at the threshold 0.5.
Each model's own predicted value takes no part in this: y_pred is read off
In a multi-class classification with three or more classes, the per-class probability vectors y_pred is the class holding the highest probability.
Both inputs are arrays of shape (N_samples, N_classes).
Where each model emits a predicted value of its own, the single value is the two values averaged with the probabilities as weights, so the model surer of its answer pulls the result toward it.
The denominator is the hybrid probability of equation (1), so the weighted soft voting of section 3.1 is what carries the two values here as well. The implementation is Appendix B.1. It checks that both probabilities lie within 0~1 before weighing them, and it raises on a row where both are zero instead of returning a number.
Rather than fixing w arbitrarily, a search (grid search) for the w that raises a performance metric (R-squared, ROC-AUC, F1-score and the like) the most on the validation dataset is recommended.
A grid search finds the optimal weight w on the validation dataset against a metric the user defines, such as R-squared, MAPE, F1-score, ROC-AUC or log loss. The metric is a callable taking (y_true, y_score), so roc_auc_score and the like are passed as they are, while f1_score and accuracy_score need the threshold first and arrive wrapped in ThresholdMetric. higher_is_better gives the direction, and passing the predicted value of each model, v_T and v_S, makes the metric score the single predicted value instead of the probability. The search runs from 0.0 to 1.0, at a step whose default of 0.01 covers 100 intervals. The return is the optimal weight best_w to give model T and the metric score at that weight, the weight of model S being 1 - best_w. The search function is Appendix B.2, and the run on synthetic data is Appendix B.3.
The optimal best_w found on the validation data is carried unchanged into the weighted sum on the test dataset for the final evaluation.
Metrics divide on what they hold against y_true. R-squared and MAPE score the single predicted value of equation (5) and are the ones that aim at the deliverable directly; F1-Score and Accuracy score y_pred, the class the threshold produces, so the weight they choose moves y_pred; ROC-AUC and Log Loss score the hybrid probability itself and leave the chosen value alone.
Table 1. Metrics for the weight search
| # | Metric | Direction | Threshold | Compared with y_true |
|---|---|---|---|---|
| 1 | r2_score |
Higher is better | Not used | v_hybrid of equation (5) |
| 2 | mean_absolute_percentage_error |
Lower is better | Not used | v_hybrid of equation (5) |
| 3 | ThresholdMetric(f1_score) |
Higher is better | Used | y_pred, the class from the threshold |
| 4 | ThresholdMetric(accuracy_score) |
Higher is better | Used | y_pred, the class from the threshold |
| 5 | roc_auc_score |
Higher is better | Not used | p_hybrid of equation (1) |
| 6 | log_loss |
Lower is better | Not used | p_hybrid of equation (1) |
Scores v_hybrid of equation (5) against y_true, which is the deliverable of this document.
- Strength: aims at the value the reader takes away; no threshold to fix; the same rule serves a continuous value and a class.
- Weakness: needs
v_Tandv_S; undefined on a row where both probabilities are zero, since that is the denominator of equation (5); squares its errors, so one wild row can decide w.
Scores v_hybrid of equation (5) against y_true, as the mean of the absolute errors divided by the true value.
- Strength: reads as a percentage, so a result stays comparable across targets of different units and sizes; a row with a large true value cannot dominate it.
- Weakness: a true value at or near zero sends it to infinity; it punishes an overshoot harder than an undershoot of the same size.
Scores y_pred, the class the threshold produces, as the harmonic mean of precision and recall on the positive class.
- Strength: shows the positive class under an imbalanced label, where a majority guess cannot hide; reads as one number at the operating point actually shipped.
- Weakness: tied to the threshold held by
ThresholdMetric, so a new threshold makes the chosen w stale; the negative class enters only through the errors it causes.
Scores y_pred, the class the threshold produces, as the fraction of rows it gets right.
- Strength: the plainest reading of the result, and it counts both classes on the same footing.
- Weakness: an imbalanced label lifts it on the majority class alone; tied to the threshold in the same way
f1_scoreis.
Scores p_hybrid of equation (1) as the ranking it induces, over every threshold at once.
- Strength: no threshold to fix, so it serves a search run before the operating point is chosen; steady under an imbalanced label.
- Weakness: unchanged by any monotone rescaling of the probability, so a badly calibrated model passes it; the single predicted value is not what it measures.
Scores p_hybrid of equation (1) against y_true, penalizing the probability by how far it sits from the label.
- Strength: the only metric here that grades the scale of the probability, so it exposes the calibration section 5 warns about.
- Weakness: a confident mistake costs it enormously, so one row can decide w; a probability at 0 or 1 sends it to infinity unless it is clipped.
The probability distributions of the two models have to be checked for a fine match. Where one model is too confident (for example, mostly near 0.05 or 0.95) and the other is cautious (for example, between 0.4 and 0.6), a plain weighted combination can give the confident model too much influence.
- Applying probability calibration
- What: calibration through
IsotonicRegressionorPlatt Scaling, applied to both probabilities before the weighted sum. - Why now: under the condition of section 5, one model confident and the other cautious, a weight alone does not correct the imbalance in influence.
- What is needed: data for the calibration, and a comparison of the optimal w and the metric scores before and after it.
- What: calibration through
N/A β no external source is cited.
- Grid Search: A search that sweeps a fixed interval at a fixed step to find the optimal value.
- Isotonic Regression: A calibration method fitting predicted probabilities to the observed frequency under a monotone increasing constraint.
- Log Loss: A metric of the disagreement between the predicted probability and the label. Lower is better.
- MAPE: Mean absolute percentage error, the mean of the absolute errors divided by the true value. Lower is better.
- Platt Scaling: A calibration method passing a model output through a logistic function to put it on a probability scale.
- Probability Calibration: The procedure of matching the probabilities a model emits to the observed frequency.
- R-squared: A metric of how much of the variance of the true value the prediction accounts for. Higher is better.
- ROC-AUC: A metric summarizing classification performance over every threshold.
- Soft Voting: A combination that averages the predicted probabilities of the models with weights to decide the final class.
- Threshold: The classification threshold that turns a probability into a final class.
- ThresholdMetric: A callable holding a class metric and the threshold it needs, so that it scores a probability like the metrics that take one directly.
from typing import Union
import numpy as np
Probability = Union[float, np.ndarray]
def check_probability(p: Probability) -> np.ndarray:
"""Check that the probability lies within 0~1.
p: predicted probability of a model
>>> check_probability(np.array([0.9, 0.5, 0.2]))
array([0.9, 0.5, 0.2])
>>> check_probability(np.array([0.9, 1.4]))
Traceback (most recent call last):
ValueError: probability outside 0~1: min=0.9, max=1.4
"""
p = np.asarray(p, dtype=float)
if p.min() < 0 or p.max() > 1:
raise ValueError(f"probability outside 0~1: min={p.min()}, max={p.max()}")
return p
def hybrid_predict_value(v_T: np.ndarray, v_S: np.ndarray, p_T: Probability, p_S: Probability,
w: float = 0.5) -> np.ndarray:
"""
v_T: predicted value of model T
v_S: predicted value of model S
p_T: predicted probability of model T (0~1)
p_S: predicted probability of model S (0~1)
w: weight given to model T (0~1)
>>> y_pred_by_t = np.array([10.0, 20.0, 30.0])
>>> y_pred_by_s = np.array([12.0, 22.0, 36.0])
>>> y_prob_by_t = np.array([0.9, 0.5, 0.2])
>>> y_prob_by_s = np.array([0.3, 0.6, 0.9])
>>> np.round(hybrid_predict_value(y_pred_by_t, y_pred_by_s, y_prob_by_t, y_prob_by_s, w=0.5), 4)
array([10.5 , 21.0909, 34.9091])
>>> hybrid_predict_value(y_pred_by_t, y_pred_by_s, np.array([0.0, 0.5, 0.2]), np.array([0.0, 0.6, 0.9]))
Traceback (most recent call last):
ValueError: both models report zero probability, so the weighted value is undefined.
"""
# both probabilities have to be on the 0~1 scale before they are weighed against each other
p_T = check_probability(p_T)
p_S = check_probability(p_S)
# confidence each model carries into the combination
weight_T = w * p_T
weight_S = (1 - w) * p_S
denominator = weight_T + weight_S
if np.any(denominator == 0):
raise ValueError("both models report zero probability, so the weighted value is undefined.")
return (weight_T * v_T + weight_S * v_S) / denominatorfrom typing import Callable
import numpy as np
from sklearn.metrics import (accuracy_score, f1_score, log_loss, mean_absolute_percentage_error, r2_score,
roc_auc_score)
Score = Callable[[np.ndarray, np.ndarray], float]
class ThresholdMetric:
"""Turn a metric that scores a class into one that scores a probability.
score_fn: metric taking (y_true, y_pred), such as f1_score or accuracy_score
threshold: classification threshold applied before the metric runs
>>> y_true = np.array([0, 0, 1, 1])
>>> p_hybrid = np.array([0.2, 0.6, 0.7, 0.4])
>>> metric = ThresholdMetric(f1_score, threshold=0.5)
>>> round(float(metric(y_true, p_hybrid)), 4)
0.5
"""
def __init__(self, score_fn: Score, threshold: float = 0.5):
self.score_fn = score_fn
self.threshold = threshold
def __call__(self, y_true: np.ndarray, p_hybrid: np.ndarray) -> float:
y_pred = (p_hybrid >= self.threshold).astype(int)
return self.score_fn(y_true, y_pred)
def find_optimal_weight(y_true: np.ndarray, p_T: np.ndarray, p_S: np.ndarray, metric: Score,
higher_is_better: bool = True, step: float = 0.01,
v_T: np.ndarray = None, v_S: np.ndarray = None) -> tuple[float, float]:
"""Search the weight w of models T and S that suits the validation dataset best, by grid search.
Parameters:
- y_true: true labels (N,)
- p_T: predicted probability of model T (N,)
- p_S: predicted probability of model S (N,)
- metric: callable taking (y_true, y_score), such as roc_auc_score or ThresholdMetric(f1_score)
- higher_is_better: direction of the metric, False for log_loss and mean_absolute_percentage_error
- step: weight step of the grid search (default: 0.01 -> 100 intervals)
- v_T: predicted value of model T (N,), which makes the metric score the single predicted value
- v_S: predicted value of model S (N,), given together with v_T
Returns:
- best_w: optimal weight for model T (model S takes 1 - best_w)
- best_score: metric score at that weight
>>> y_true = np.array([0, 0, 1, 1])
>>> p_T = np.array([0.2, 0.3, 0.7, 0.8])
>>> p_S = np.array([0.6, 0.4, 0.5, 0.3])
>>> best_w, best_score = find_optimal_weight(y_true, p_T, p_S, metric=roc_auc_score, step=0.25)
>>> float(best_w), round(float(best_score), 4)
(0.5, 1.0)
>>> best_w, best_score = find_optimal_weight(
... y_true, p_T, p_S, metric=log_loss, higher_is_better=False, step=0.25
... )
>>> float(best_w), round(float(best_score), 4)
(1.0, 0.2899)
>>> y_value = np.array([10.0, 20.0, 30.0, 40.0])
>>> v_T = np.array([11.0, 19.0, 33.0, 37.0])
>>> v_S = np.array([14.0, 25.0, 26.0, 44.0])
>>> best_w, best_score = find_optimal_weight(
... y_value, p_T, p_S, metric=r2_score, step=0.25, v_T=v_T, v_S=v_S
... )
>>> float(best_w), round(float(best_score), 4)
(0.75, 0.9707)
>>> best_w, best_score = find_optimal_weight(
... y_true, p_T, p_S, metric=ThresholdMetric(accuracy_score), step=0.25
... )
>>> float(best_w), round(float(best_score), 4)
(0.5, 1.0)
"""
if not callable(metric):
raise TypeError(f"metric must be callable, not {type(metric).__name__}.")
if (v_T is None) != (v_S is None):
raise ValueError("v_T and v_S are given together or not at all.")
weights = np.arange(0.0, 1.0 + step, step)
best_w = None
best_score = -float("inf") if higher_is_better else float("inf")
for w in weights:
# weighted average probability
p_hybrid = w * p_T + (1 - w) * p_S
# the metric scores the single predicted value where both models report one
if v_T is None:
score = metric(y_true, p_hybrid)
else:
score = metric(y_true, hybrid_predict_value(v_T, v_S, p_T, p_S, w))
# keep the best so far
if higher_is_better:
if score > best_score:
best_score = score
best_w = round(w, 4)
else:
if score < best_score:
best_score = score
best_w = round(w, 4)
return best_w, best_score# --- synthetic validation data ---
np.random.seed(42)
N_samples = 1000
# ground truth
y_true = np.random.randint(0, 2, size=N_samples)
# probability from model T, relatively close to the truth
y_prob_by_t = y_true * 0.7 + np.random.normal(0, 0.2, size=N_samples)
y_prob_by_t = np.clip(y_prob_by_t, 0.01, 1)
# probability from model S
y_prob_by_s = y_true * 0.5 + np.random.normal(0, 0.3, size=N_samples)
y_prob_by_s = np.clip(y_prob_by_s, 0.01, 1)
# the class each model predicts on its own, at the 0.5 threshold
y_pred_by_t = (y_prob_by_t >= 0.5).astype(int)
y_pred_by_s = (y_prob_by_s >= 0.5).astype(int)
# --- the first ten rows of the sample ---
print("y_true :", y_true[:10])
print("y_pred_by_t:", y_pred_by_t[:10])
print("y_pred_by_s:", y_pred_by_s[:10])
print("y_prob_by_t:", np.round(y_prob_by_t[:10], 4))
print("y_prob_by_s:", np.round(y_prob_by_s[:10], 4))
# --- run the grid search ---
# 1. optimize on F1-score, which needs the threshold the class is read at
best_w_f1, best_score_f1 = find_optimal_weight(
y_true, y_prob_by_t, y_prob_by_s, metric=ThresholdMetric(f1_score, threshold=0.5)
)
print(f"[F1-Score] best w: {best_w_f1} | score: {best_score_f1:.4f}")
# 2. optimize on ROC-AUC
best_w_auc, best_score_auc = find_optimal_weight(
y_true, y_prob_by_t, y_prob_by_s, metric=roc_auc_score
)
print(f"[ROC-AUC] best w: {best_w_auc} | score: {best_score_auc:.4f}")
# 3. optimize on log loss, lower is better
best_w_loss, best_score_loss = find_optimal_weight(
y_true, y_prob_by_t, y_prob_by_s, metric=log_loss, higher_is_better=False
)
print(f"[Log Loss] best w: {best_w_loss} | score: {best_score_loss:.4f}")
# 4. optimize on R-squared, which scores the single predicted value itself
best_w_r2, best_score_r2 = find_optimal_weight(
y_true, y_prob_by_t, y_prob_by_s, metric=r2_score,
v_T=y_pred_by_t, v_S=y_pred_by_s
)
print(f"[R-squared] best w: {best_w_r2} | score: {best_score_r2:.4f}")
# 5. optimize on MAPE, which scores the same value on a percentage scale
best_w_mape, best_score_mape = find_optimal_weight(
y_true, y_prob_by_t, y_prob_by_s, metric=mean_absolute_percentage_error,
higher_is_better=False, v_T=y_pred_by_t, v_S=y_pred_by_s
)
print(f"[MAPE] best w: {best_w_mape} | score: {best_score_mape:.4f}")
# --- the single predicted value at the weight R-squared chose ---
v_hybrid = hybrid_predict_value(
y_pred_by_t, y_pred_by_s, y_prob_by_t, y_prob_by_s, w=best_w_r2
)
print("v_hybrid :", np.round(v_hybrid[:10], 4))The five arrays printed first are the head of the sample, ten rows of it, the five lines after them are the search result, and the last line is the single predicted value at the weight R-squared chose. The MAPE score runs to 1e13 because y_true is 0 on most rows and the metric divides by it, the weakness section 4.2 names.
y_true : [0 1 0 0 0 1 0 0 0 1]
y_pred_by_t: [0 1 0 0 0 1 0 0 0 1]
y_pred_by_s: [0 1 0 0 0 0 1 0 0 1]
y_prob_by_t: [0.0684 1. 0.1901 0.01 0.01 0.7984 0.01 0.3663 0.2359 0.6062]
y_prob_by_s: [0.3905 0.9685 0.01 0.01 0.138 0.2967 0.604 0.041 0.01 0.5554]
[F1-Score] best w: 0.78 | score: 0.9174
[ROC-AUC] best w: 0.73 | score: 0.9968
[Log Loss] best w: 1.0 | score: 0.2542
[R-squared] best w: 0.7 | score: 0.7127
[MAPE] best w: 1.0 | score: 13510798882111.5684
v_hybrid : [0. 1. 0. 0. 0. 0.8626 0.9628 0. 0. 1. ]
Version 32 | Created: 2026-09-11 | Updated: 2026-11-07 13:46 UTC
- 1. Purpose
- 2. Summary
- 3. Principle
- 4. Optimal Weight Search
- 5. Cautions
- 6. Further Work
- References
- Appendix A. Terminology
- Appendix B. Python Implementation
- Problem Statement: 볡μμ λͺ¨λΈμμ κ³μ°ν μμΈ‘κ°μ νλλ‘ ν©μΉλ κ°λ¨ν λ°©λ²μ΄ μλ€.
- Goal: λ λͺ¨λΈμμ κ°κ° μμΈ‘ κ°κ³Ό νλ₯ μ λ΄λμ λ, λ νλ₯ μ κ³ λ €ν λ¨μΌ μμΈ‘κ°μ μ μνκ³ μ νλ€.
- Non-Goal: λͺ¨λΈ μ체μ νμ΅κ³Ό κ°μ μ νμ§ μλλ€.
λ¨μΌ μμΈ‘κ°μ λ νλ₯ μμ λμ΅λλ€. y_pred λ λ νλ₯ μ κ°μ€ νκ· μμ λ€μ μ½μ΄λ΄κ³ , ν΄λμ€κ° μλ μμΈ‘ κ°μ κ·Έ λ νλ₯ μ κ°μ€μΉλ‘ μΌμ νκ· ν©λλ€. λ λͺ¨λΈ Tμ Sκ° λͺ¨λ μμΈ‘ νλ₯ (
λ λͺ¨λΈμ νλ₯ κ°
μ΄μ§ λΆλ₯μ μμΈ‘κ° y_pred λ μκ³κ° 0.5 λ₯Ό κΈ°μ€μΌλ‘ κ°λ¦½λλ€.
κ° λͺ¨λΈμ΄ λ΄λμ μμΈ‘κ°μ μ¬κΈ°μ μ°μ΄μ§ μμ΅λλ€. y_pred λ
ν΄λμ€κ° 3κ° μ΄μμΈ λ€μ€ ν΄λμ€ λΆλ₯μμλ κ° ν΄λμ€λ³ νλ₯ λ²‘ν° y_pred λ‘ μΌμ΅λλ€.
μ
λ ₯ λ κ°λ λͺ¨λ (N_samples, N_classes) νμμ λ°°μ΄μ
λλ€.
κ° λͺ¨λΈμ΄ μμΈ‘ κ°μ ν¨κ» λ΄λλ κ²½μ°, λ¨μΌ μμΈ‘κ°μ λ κ°μ νλ₯ λ‘ κ°μ€ νκ· ν κ²μ λλ€. μκΈ° λ΅μ λ νμ νλ λͺ¨λΈ μͺ½μΌλ‘ κ²°κ³Όκ° λ립λλ€.
λΆλͺ¨λ μ (1) μ νμ΄λΈλ¦¬λ νλ₯ μ΄λ―λ‘, κΌμ§ 3.1 μ Soft Voting μ΄ μ¬κΈ°μλ λ κ°μ μ€μ΄ λλ¦ λλ€. ꡬνμ Appendix B.1 μ λλ€. κ°μ€ν©μ μμ λ νλ₯ μ΄ 0~1 μμ μλμ§ νμΈνλ©°, λ νλ₯ μ΄ λͺ¨λ 0 μΈ νμμλ κ°μ λλ €μ£Όλ λμ μ€λ₯λ₯Ό λ λλ€.
w κ°μ μμλ‘ μ ν기보λ€λ, Validation Datasetμμ μ±λ₯ μ§ν (R-squared, ROC-AUC, F1-score λ±) λ₯Ό κ°μ₯ λμ¬μ£Όλ wλ₯Ό νμ (Grid Search) νμ¬ μ μ νλ κ²μ κΆμ₯ν©λλ€.
Validation λ°μ΄ν°μ
μμ R-squared, MAPE, F1-score, ROC-AUC, Log-Loss λ± μ¬μ©μκ° μ μν νκ° μ§νλ₯Ό κΈ°μ€μΌλ‘ μ΅μ μ κ°μ€μΉ wλ₯Ό Grid Searchλ‘ νμν©λλ€. μ§νλ (y_true, y_score) λ₯Ό λ°λ callable μ΄λ―λ‘ roc_auc_score κ°μ ν¨μλ κ·Έλλ‘ λκΈ°κ³ , f1_score μ accuracy_score λ μκ³κ°μ λ¨Όμ λ°μμΌ νλ―λ‘ ThresholdMetric μ μΈμ λκΉλλ€. λ°©ν₯μ higher_is_better κ° μ νκ³ , κ° λͺ¨λΈμ μμΈ‘ κ° v_T, v_S λ₯Ό ν¨κ» λκΈ°λ©΄ μ§νκ° νλ₯ λμ λ¨μΌ μμΈ‘κ°μ μ±μ ν©λλ€. νμ ꡬκ°μ 0.0 μμ 1.0 κΉμ§μ΄κ³ , κ°κ²©μ κΈ°λ³Έκ° 0.01 λ‘ 100κ° κ΅¬κ°μ νμ΅λλ€. λ°νκ°μ λͺ¨λΈ T μ λΆμ¬ν μ΅μ κ°μ€μΉ best_w μ κ·Έ κ°μ€μΉμμμ νκ° μ§ν μ μμ΄λ©°, λͺ¨λΈ S μ κ°μ€μΉλ 1 - best_w μ
λλ€. νμ ν¨μλ Appendix B.2 μ΄κ³ , κ°μ λ°μ΄ν°λ₯Ό νμ©ν μ€ν μμλ Appendix B.3 μ
λλ€.
Validation λ°μ΄ν°λ‘ μ°ΎμλΈ μ΅μ μ best_w λ₯Ό κ·Έλλ‘ Test λ°μ΄ν°μ
μ κ°μ€ν© κ³μ°μ μ μ©νμ¬ μ΅μ’
νκ°λ₯Ό μννλ©΄ λ©λλ€.
μ§νλ y_true μ 무μμ λλμ§λ‘ κ°λ¦½λλ€. R-squared μ MAPE λ μ (5) μ λ¨μΌ μμΈ‘κ°μ μ¬μ΄ μ°μΆλ¬Όμ λ°λ‘ 겨λ₯νκ³ , F1-Score μ Accuracy λ threshold κ° λ§λ ν΄λμ€ y_pred λ₯Ό μ¬λ―λ‘ μ΄λ€μ΄ κ³ λ₯Έ κ°μ€μΉλ y_pred λ₯Ό μμ§μ΄λ©°, ROC-AUC μ Log Loss λ νμ΄λΈλ¦¬λ νλ₯ μ체λ₯Ό μ¬μ΄ κ³ λ₯Έ κ°μ 건λλ¦¬μ§ μμ΅λλ€.
Table 1. Metrics for the weight search
| # | Metric | Direction | Threshold | Compared with y_true |
|---|---|---|---|---|
| 1 | r2_score |
Higher is better | Not used | v_hybrid of equation (5) |
| 2 | mean_absolute_percentage_error |
Lower is better | Not used | v_hybrid of equation (5) |
| 3 | ThresholdMetric(f1_score) |
Higher is better | Used | y_pred, the class from the threshold |
| 4 | ThresholdMetric(accuracy_score) |
Higher is better | Used | y_pred, the class from the threshold |
| 5 | roc_auc_score |
Higher is better | Not used | p_hybrid of equation (1) |
| 6 | log_loss |
Lower is better | Not used | p_hybrid of equation (1) |
μ (5) μ v_hybrid λ₯Ό y_true μ λλλ€. μ΄ λ¬Έμμ μ°μΆλ¬Όμ΄ λ°λ‘ κ·Έ κ°μ
λλ€.
- μ₯μ : λ μκ° κ°μ Έκ°λ κ°μ μ§μ 겨λ₯. μκ³κ°μ μ ν νμ μμ. μ°μκ°κ³Ό ν΄λμ€μ κ°μ κ·μΉμΌλ‘ μ μ©.
- λ¨μ :
v_T,v_Sκ° μμ΄μΌ ν¨. λ νλ₯ μ΄ λͺ¨λ 0 μΈ νμμλ μ (5) μ λΆλͺ¨κ° 0 μ΄λΌ μ μλμ§ μμ. μ€μ°¨λ₯Ό μ κ³±νλ―λ‘ ν νμ ν° μ€μ°¨κ° w λ₯Ό μ’μ°.
μ (5) μ v_hybrid λ₯Ό y_true μ λμ΄, μ λ μ€μ°¨λ₯Ό μ λ΅μΌλ‘ λλ κ°μ νκ· μ λ
λλ€.
- μ₯μ : λ°±λΆμ¨λ‘ μ½νλ―λ‘ λ¨μμ ν¬κΈ°κ° λ€λ₯Έ λμλΌλ¦¬ κ²°κ³Όλ₯Ό κ²¬μ€ μ μμ. μ λ΅μ΄ ν° νμ΄ μ§νλ₯Ό λ μ°¨μ§νμ§ μμ.
- λ¨μ : μ λ΅μ΄ 0 μ΄κ±°λ 0 μ κ°κΉμ°λ©΄ λ°μ°. κ°μ ν¬κΈ°λΌλ κ³ΌλμμΈ‘μ λ²μ μ΄ κ³ΌμμμΈ‘λ³΄λ€ νΌ.
threshold κ° λ§λ ν΄λμ€ y_pred λ₯Ό μ λ°λμ μ¬νμ¨μ μ‘°ν νκ· μΌλ‘ μ½λλ€.
- μ₯μ : λ μ΄λΈμ΄ λΆκ· νμΌ λ μμ± ν΄λμ€μ μ±λ₯μ΄ λλ¬λ¨. μ€μ λ‘ μ°λ λμμ μμμ μ±λ₯μ ν μ«μλ‘ μ½μ.
- λ¨μ :
ThresholdMetricμ΄ μ₯ μκ³κ°μ λ¬Άμ¬ μμ΄ μκ³κ°μ΄ λ°λλ©΄ κ³ λ₯Έ w κ° λ‘μ. μμ± ν΄λμ€λ κ·Έκ²μ΄ λΆλ₯Έ μ€λ₯λ‘λ§ λ°μ.
threshold κ° λ§λ ν΄λμ€ y_pred κ°μ΄λ° λ§ν νμ λΉμ¨μ
λλ€.
- μ₯μ : κ²°κ³Όλ₯Ό κ°μ₯ λ¨μνκ² μ½λ λ°©μ. λ ν΄λμ€λ₯Ό κ°μ 무κ²λ‘ μ .
- λ¨μ : λ μ΄λΈμ΄ λΆκ· νμ΄λ©΄ λ€μ ν΄λμ€λ§ λ§νλ λκ² λμ΄.
f1_scoreμ κ°μ λ°©μμΌλ‘ μκ³κ°μ λ¬Άμ.
μ (1) μ p_hybrid κ° λ§λλ μμλ₯Ό λͺ¨λ μκ³κ°μ κ±Έμ³ νκΊΌλ²μ μ½λλ€.
- μ₯μ : μκ³κ°μ μ ν νμκ° μμ΄ λμμ μ μ νκΈ° μ μ νμμ λ§μ. λ μ΄λΈ λΆκ· νμ κ²¬κ³ .
- λ¨μ : νλ₯ μ λ¨μ‘° λ³νν΄λ κ°μ΄ κ·Έλλ‘λΌ calibration μ΄ μ΄κΈλ λͺ¨λΈλ ν΅κ³Ό. λ¨μΌ μμΈ‘κ°μ μ¬λ μ§νκ° μλ.
μ (1) μ p_hybrid λ₯Ό y_true μ λμ΄, νλ₯ μ΄ μ λ΅μμ μΌλ§λ λ¨μ΄μ Έ μλμ§λ‘ λ²μ μ λ§€κΉλλ€.
- μ₯μ : νλ₯ μ λκΈκΉμ§ μ±μ νλ μ μΌν μ§νλΌ, κΌμ§ 5 κ° κ²½κ³ νλ calibration μνκ° λλ¬λ¨.
- λ¨μ : νμ μ κ°κ³ νλ¦° ν νμ λ²μ μ΄ λ§€μ° μ»€μ κ·Έ νμ΄ w λ₯Ό μ’μ°. νλ₯ μ΄ 0 μ΄λ 1 μ΄λ©΄ ν΄λ¦¬ν μμ΄λ λ°μ°.
λ λͺ¨λΈμ νλ₯ λΆν¬κ° μ κ΅νκ² λ§μΆμ΄μ Έ μλμ§ νμΈν΄μΌ ν©λλ€. ν λͺ¨λΈμ΄ νλ₯ μ λ무 κ³Όμ (μ: λλΆλΆ 0.05 λλ 0.95 κ·Όμ²) νκ³ λ€λ₯Έ λͺ¨λΈμ μ μ€ν κ²½μ° (μ: 0.4βΌ0.6 μ¬μ΄), λ¨μ κ°μ€μΉ μ‘°ν© μ κ³Όμ νλ λͺ¨λΈμ μν₯λ ₯μ΄ κ³Όλνκ² μ»€μ§ μ μμ΅λλ€.
- νλ₯ calibration μ μ©
- 무μ:
IsotonicRegressionμ΄λPlatt Scalingμ ν΅ν calibration μ λ λͺ¨λΈμ νλ₯ μ μ μ©ν λ€ κ°μ€ν©. - μ μ§κΈ: κΌμ§ 5 μ 쑰건, μ¦ ν λͺ¨λΈμ΄ κ³Όμ νκ³ λ€λ₯Έ λͺ¨λΈμ΄ μ μ€ν μνμμλ κ°μ€μΉλ§μΌλ‘ μν₯λ ₯μ λΆκ· νμ λ°λ‘μ‘μ§ λͺ»ν¨.
- 무μμ΄ νμ: Calibration μ μΈ λ°μ΄ν°μ, calibration μ νμ μ΅μ w λ° μ§ν μ μ λΉκ΅.
- 무μ:
N/A β μΈλΆ μΆμ²λ₯Ό μΈμ©νμ§ μμ.
- Grid Search: μ ν΄μ§ ꡬκ°μ μΌμ κ°κ²©μΌλ‘ νμ΄ μ΅μ κ°μ μ°Ύλ νμ.
- Isotonic Regression: λ¨μ‘° μ¦κ° μ μ½ μλ μμΈ‘ νλ₯ μ μ€μ λΉλμ λ§μΆλ κ΅μ λ°©λ².
- Log Loss: μμΈ‘ νλ₯ κ³Ό μ λ΅μ λΆμΌμΉλ₯Ό μ¬λ μ§ν. μμμλ‘ μ’μ.
- MAPE: Mean absolute percentage error, the mean of the absolute errors divided by the true value. Lower is better.
- Platt Scaling: λͺ¨λΈμ μΆλ ₯μ logistic ν¨μμ ν΅κ³ΌμμΌ νλ₯ λ‘ λ§μΆλ κ΅μ λ°©λ².
- Probability Calibration: λͺ¨λΈμ΄ λ΄λλ νλ₯ μ μ€μ λΉλμ λ§μΆλ μ μ°¨.
- R-squared: A metric of how much of the variance of the true value the prediction accounts for. Higher is better.
- ROC-AUC: λͺ¨λ μκ³κ°μ κ±ΈμΉ λΆλ₯ μ±λ₯μ νλλ‘ μμ½ν μ§ν.
- Soft Voting: κ° λͺ¨λΈμ μμΈ‘ νλ₯ μ κ°μ€ νκ· νμ¬ μ΅μ’ ν΄λμ€λ₯Ό μ νλ κ²°ν© λ°©μ.
- Threshold: νλ₯ μ μ΅μ’ ν΄λμ€λ‘ λ³ννλ λΆλ₯ μκ³κ°.
- ThresholdMetric: ν΄λμ€λ₯Ό μ¬λ μ§νμ κ·Έκ²μ΄ νμν μκ³κ°μ ν¨κ» μ₯ callable. νλ₯ μ λ°λ‘ λ°λ μ§νλ€κ³Ό κ°μ λ°©μμΌλ‘ νλ₯ μ μ±μ νλ€.
from typing import Union
import numpy as np
Probability = Union[float, np.ndarray]
def check_probability(p: Probability) -> np.ndarray:
"""Check that the probability lies within 0~1.
p: predicted probability of a model
>>> check_probability(np.array([0.9, 0.5, 0.2]))
array([0.9, 0.5, 0.2])
>>> check_probability(np.array([0.9, 1.4]))
Traceback (most recent call last):
ValueError: probability outside 0~1: min=0.9, max=1.4
"""
p = np.asarray(p, dtype=float)
if p.min() < 0 or p.max() > 1:
raise ValueError(f"probability outside 0~1: min={p.min()}, max={p.max()}")
return p
def hybrid_predict_value(v_T: np.ndarray, v_S: np.ndarray, p_T: Probability, p_S: Probability,
w: float = 0.5) -> np.ndarray:
"""
v_T: predicted value of model T
v_S: predicted value of model S
p_T: predicted probability of model T (0~1)
p_S: predicted probability of model S (0~1)
w: weight given to model T (0~1)
>>> y_pred_by_t = np.array([10.0, 20.0, 30.0])
>>> y_pred_by_s = np.array([12.0, 22.0, 36.0])
>>> y_prob_by_t = np.array([0.9, 0.5, 0.2])
>>> y_prob_by_s = np.array([0.3, 0.6, 0.9])
>>> np.round(hybrid_predict_value(y_pred_by_t, y_pred_by_s, y_prob_by_t, y_prob_by_s, w=0.5), 4)
array([10.5 , 21.0909, 34.9091])
>>> hybrid_predict_value(y_pred_by_t, y_pred_by_s, np.array([0.0, 0.5, 0.2]), np.array([0.0, 0.6, 0.9]))
Traceback (most recent call last):
ValueError: both models report zero probability, so the weighted value is undefined.
"""
# both probabilities have to be on the 0~1 scale before they are weighed against each other
p_T = check_probability(p_T)
p_S = check_probability(p_S)
# confidence each model carries into the combination
weight_T = w * p_T
weight_S = (1 - w) * p_S
denominator = weight_T + weight_S
if np.any(denominator == 0):
raise ValueError("both models report zero probability, so the weighted value is undefined.")
return (weight_T * v_T + weight_S * v_S) / denominatorfrom typing import Callable
import numpy as np
from sklearn.metrics import (accuracy_score, f1_score, log_loss, mean_absolute_percentage_error, r2_score,
roc_auc_score)
Score = Callable[[np.ndarray, np.ndarray], float]
class ThresholdMetric:
"""Turn a metric that scores a class into one that scores a probability.
score_fn: metric taking (y_true, y_pred), such as f1_score or accuracy_score
threshold: classification threshold applied before the metric runs
>>> y_true = np.array([0, 0, 1, 1])
>>> p_hybrid = np.array([0.2, 0.6, 0.7, 0.4])
>>> metric = ThresholdMetric(f1_score, threshold=0.5)
>>> round(float(metric(y_true, p_hybrid)), 4)
0.5
"""
def __init__(self, score_fn: Score, threshold: float = 0.5):
self.score_fn = score_fn
self.threshold = threshold
def __call__(self, y_true: np.ndarray, p_hybrid: np.ndarray) -> float:
y_pred = (p_hybrid >= self.threshold).astype(int)
return self.score_fn(y_true, y_pred)
def find_optimal_weight(y_true: np.ndarray, p_T: np.ndarray, p_S: np.ndarray, metric: Score,
higher_is_better: bool = True, step: float = 0.01,
v_T: np.ndarray = None, v_S: np.ndarray = None) -> tuple[float, float]:
"""Search the weight w of models T and S that suits the validation dataset best, by grid search.
Parameters:
- y_true: true labels (N,)
- p_T: predicted probability of model T (N,)
- p_S: predicted probability of model S (N,)
- metric: callable taking (y_true, y_score), such as roc_auc_score or ThresholdMetric(f1_score)
- higher_is_better: direction of the metric, False for log_loss and mean_absolute_percentage_error
- step: weight step of the grid search (default: 0.01 -> 100 intervals)
- v_T: predicted value of model T (N,), which makes the metric score the single predicted value
- v_S: predicted value of model S (N,), given together with v_T
Returns:
- best_w: optimal weight for model T (model S takes 1 - best_w)
- best_score: metric score at that weight
>>> y_true = np.array([0, 0, 1, 1])
>>> p_T = np.array([0.2, 0.3, 0.7, 0.8])
>>> p_S = np.array([0.6, 0.4, 0.5, 0.3])
>>> best_w, best_score = find_optimal_weight(y_true, p_T, p_S, metric=roc_auc_score, step=0.25)
>>> float(best_w), round(float(best_score), 4)
(0.5, 1.0)
>>> best_w, best_score = find_optimal_weight(
... y_true, p_T, p_S, metric=log_loss, higher_is_better=False, step=0.25
... )
>>> float(best_w), round(float(best_score), 4)
(1.0, 0.2899)
>>> y_value = np.array([10.0, 20.0, 30.0, 40.0])
>>> v_T = np.array([11.0, 19.0, 33.0, 37.0])
>>> v_S = np.array([14.0, 25.0, 26.0, 44.0])
>>> best_w, best_score = find_optimal_weight(
... y_value, p_T, p_S, metric=r2_score, step=0.25, v_T=v_T, v_S=v_S
... )
>>> float(best_w), round(float(best_score), 4)
(0.75, 0.9707)
>>> best_w, best_score = find_optimal_weight(
... y_true, p_T, p_S, metric=ThresholdMetric(accuracy_score), step=0.25
... )
>>> float(best_w), round(float(best_score), 4)
(0.5, 1.0)
"""
if not callable(metric):
raise TypeError(f"metric must be callable, not {type(metric).__name__}.")
if (v_T is None) != (v_S is None):
raise ValueError("v_T and v_S are given together or not at all.")
weights = np.arange(0.0, 1.0 + step, step)
best_w = None
best_score = -float("inf") if higher_is_better else float("inf")
for w in weights:
# weighted average probability
p_hybrid = w * p_T + (1 - w) * p_S
# the metric scores the single predicted value where both models report one
if v_T is None:
score = metric(y_true, p_hybrid)
else:
score = metric(y_true, hybrid_predict_value(v_T, v_S, p_T, p_S, w))
# keep the best so far
if higher_is_better:
if score > best_score:
best_score = score
best_w = round(w, 4)
else:
if score < best_score:
best_score = score
best_w = round(w, 4)
return best_w, best_score# --- synthetic validation data ---
np.random.seed(42)
N_samples = 1000
# ground truth
y_true = np.random.randint(0, 2, size=N_samples)
# probability from model T, relatively close to the truth
y_prob_by_t = y_true * 0.7 + np.random.normal(0, 0.2, size=N_samples)
y_prob_by_t = np.clip(y_prob_by_t, 0.01, 1)
# probability from model S
y_prob_by_s = y_true * 0.5 + np.random.normal(0, 0.3, size=N_samples)
y_prob_by_s = np.clip(y_prob_by_s, 0.01, 1)
# the class each model predicts on its own, at the 0.5 threshold
y_pred_by_t = (y_prob_by_t >= 0.5).astype(int)
y_pred_by_s = (y_prob_by_s >= 0.5).astype(int)
# --- the first ten rows of the sample ---
print("y_true :", y_true[:10])
print("y_pred_by_t:", y_pred_by_t[:10])
print("y_pred_by_s:", y_pred_by_s[:10])
print("y_prob_by_t:", np.round(y_prob_by_t[:10], 4))
print("y_prob_by_s:", np.round(y_prob_by_s[:10], 4))
# --- run the grid search ---
# 1. optimize on F1-score, which needs the threshold the class is read at
best_w_f1, best_score_f1 = find_optimal_weight(
y_true, y_prob_by_t, y_prob_by_s, metric=ThresholdMetric(f1_score, threshold=0.5)
)
print(f"[F1-Score] best w: {best_w_f1} | score: {best_score_f1:.4f}")
# 2. optimize on ROC-AUC
best_w_auc, best_score_auc = find_optimal_weight(
y_true, y_prob_by_t, y_prob_by_s, metric=roc_auc_score
)
print(f"[ROC-AUC] best w: {best_w_auc} | score: {best_score_auc:.4f}")
# 3. optimize on log loss, lower is better
best_w_loss, best_score_loss = find_optimal_weight(
y_true, y_prob_by_t, y_prob_by_s, metric=log_loss, higher_is_better=False
)
print(f"[Log Loss] best w: {best_w_loss} | score: {best_score_loss:.4f}")
# 4. optimize on R-squared, which scores the single predicted value itself
best_w_r2, best_score_r2 = find_optimal_weight(
y_true, y_prob_by_t, y_prob_by_s, metric=r2_score,
v_T=y_pred_by_t, v_S=y_pred_by_s
)
print(f"[R-squared] best w: {best_w_r2} | score: {best_score_r2:.4f}")
# 5. optimize on MAPE, which scores the same value on a percentage scale
best_w_mape, best_score_mape = find_optimal_weight(
y_true, y_prob_by_t, y_prob_by_s, metric=mean_absolute_percentage_error,
higher_is_better=False, v_T=y_pred_by_t, v_S=y_pred_by_s
)
print(f"[MAPE] best w: {best_w_mape} | score: {best_score_mape:.4f}")
# --- the single predicted value at the weight R-squared chose ---
v_hybrid = hybrid_predict_value(
y_pred_by_t, y_pred_by_s, y_prob_by_t, y_prob_by_s, w=best_w_r2
)
print("v_hybrid :", np.round(v_hybrid[:10], 4))λ¨Όμ μ°νλ λ€μ― λ°°μ΄μ΄ νλ³Έμ 머리 μ΄ νμ΄κ³ , κ·Έ λ€ λ€μ― μ€μ΄ νμ κ²°κ³Όμ΄λ©°, λ§μ§λ§ μ€μ΄ R-squared κ° κ³ λ₯Έ κ°μ€μΉμμμ λ¨μΌ μμΈ‘κ°μ
λλ€. MAPE μ μκ° 1e13 μ μ΄λ₯΄λ κ²μ y_true κ° λλΆλΆμ νμμ 0 μ΄κ³ κ·Έ κ°μΌλ‘ λλκΈ° λλ¬Έμ΄λ©°, κΌμ§ 4.2 κ° μ μ λ¨μ μ΄ κ·Έλλ‘ λλ¬λ κ²μ
λλ€.
y_true : [0 1 0 0 0 1 0 0 0 1]
y_pred_by_t: [0 1 0 0 0 1 0 0 0 1]
y_pred_by_s: [0 1 0 0 0 0 1 0 0 1]
y_prob_by_t: [0.0684 1. 0.1901 0.01 0.01 0.7984 0.01 0.3663 0.2359 0.6062]
y_prob_by_s: [0.3905 0.9685 0.01 0.01 0.138 0.2967 0.604 0.041 0.01 0.5554]
[F1-Score] best w: 0.78 | score: 0.9174
[ROC-AUC] best w: 0.73 | score: 0.9968
[Log Loss] best w: 1.0 | score: 0.2542
[R-squared] best w: 0.7 | score: 0.7127
[MAPE] best w: 1.0 | score: 13510798882111.5684
v_hybrid : [0. 1. 0. 0. 0. 0.8626 0.9628 0. 0. 1. ]
