|

Single Predicted Value From Two Models

Single Predicted Value From Two Models

Version 31 | Created: 2026-09-11 | Updated: 2026-11-07 13:46 UTC

1. Purpose

  • 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.

2. Summary

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 ($p_T$, $p_S$), soft voting, a weighted average of the probabilities that reflects the confidence of each model precisely, is the most effective method. The weight w comes from a grid search on a validation dataset (section 4.1) rather than from a guess, and the value found is carried unchanged into the weighted sum on the test dataset.

3. Principle

3.1 Weighted Soft Voting

A weight w ($0 \le w \le 1$) applied to the probabilities $p_T$ and $p_S$ of the two models gives the hybrid probability $p_{\mathrm{hybrid}}$.

$$p_{\mathrm{hybrid}} = w \cdot p_T + (1 - w) \cdot p_S \hspace{19em} (1)$$

The prediction y_pred of a binary classification is decided at the threshold 0.5.

$$y_{\mathrm{pred}} = \begin{cases} 1 & \mathrm{if}\ p_{\mathrm{hybrid}} \ge 0.5 \\\ 0 & \mathrm{otherwise} \end{cases} \hspace{15em} (2)$$

Each model's own predicted value takes no part in this: y_pred is read off $p_{\mathrm{hybrid}}$, and the share a model holds in it is what the weight w sets. Section 3.3 is the rule for the predicted values themselves.

3.2 Multi-Class Extension

In a multi-class classification with three or more classes, the per-class probability vectors $p_T$ and $p_S$ are summed with the weight, and y_pred is the class holding the highest probability.

$$\mathbf{p}_{\mathrm{hybrid}} = w \cdot \mathbf{p}_T + (1 - w) \cdot \mathbf{p}_S \hspace{19em} (3)$$ $$y_{\mathrm{pred}} = \arg\max \left( \mathbf{p}_{\mathrm{hybrid}} \right) \hspace{19em} (4)$$

Both inputs are arrays of shape (N_samples, N_classes).

3.3 Single Predicted Value

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.

$$v_{\mathrm{hybrid}} = \frac{w \cdot p_T \cdot v_T + (1 - w) \cdot p_S \cdot v_S}{w \cdot p_T + (1 - w) \cdot p_S} \hspace{15em} (5)$$

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.

4. Optimal Weight Search

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.

4.1 Grid Search

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.

$$p_{\mathrm{hybrid,test}} = w_{\mathrm{best}} \cdot p_{T,\mathrm{test}} + (1 - w_{\mathrm{best}}) \cdot p_{S,\mathrm{test}} \hspace{19em} (6)$$

4.2 Metric Selection

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)

r2_score

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_T and v_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.

mean_absolute_percentage_error

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.

ThresholdMetric(f1_score)

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.

ThresholdMetric(accuracy_score)

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_score is.

roc_auc_score

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.

log_loss

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.

5. Cautions

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.

6. Further Work

  • Applying probability calibration
    • What: calibration through IsotonicRegression or Platt 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.

References

N/A β€” no external source is cited.


Appendix A. Terminology

  • 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.

Appendix B. Python Implementation

B.1 Single Predicted Value

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) / denominator

B.2 Optimal Weight Search

from 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

B.3 Execution Example

# --- 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.    ]

Single Predicted Value From Two Models

Version 32 | Created: 2026-09-11 | Updated: 2026-11-07 13:46 UTC

1. Purpose

  • Problem Statement: 볡수의 λͺ¨λΈμ—μ„œ κ³„μ‚°ν•œ μ˜ˆμΈ‘κ°’μ„ ν•˜λ‚˜λ‘œ ν•©μΉ˜λŠ” κ°„λ‹¨ν•œ 방법이 μ—†λ‹€.
  • Goal: 두 λͺ¨λΈμ—μ„œ 각각 예츑 κ°’κ³Ό ν™•λ₯ μ„ 내놓을 λ•Œ, 두 ν™•λ₯ μ„ κ³ λ €ν•œ 단일 μ˜ˆμΈ‘κ°’μ„ μ œμ‹œν•˜κ³ μž ν•œλ‹€.
  • Non-Goal: λͺ¨λΈ 자체의 ν•™μŠ΅κ³Ό κ°œμ„ μ€ ν•˜μ§€ μ•ŠλŠ”λ‹€.

2. Summary

단일 μ˜ˆμΈ‘κ°’μ€ 두 ν™•λ₯ μ—μ„œ λ‚˜μ˜΅λ‹ˆλ‹€. y_pred λŠ” 두 ν™•λ₯ μ˜ 가쀑 ν‰κ· μ—μ„œ λ‹€μ‹œ 읽어내고, ν΄λž˜μŠ€κ°€ μ•„λ‹Œ 예츑 값은 κ·Έ 두 ν™•λ₯ μ„ κ°€μ€‘μΉ˜λ‘œ μ‚Όμ•„ ν‰κ· ν•©λ‹ˆλ‹€. 두 λͺ¨λΈ T와 Sκ°€ λͺ¨λ‘ 예츑 ν™•λ₯  ($p_T$, $p_S$) 을 μ œκ³΅ν•œλ‹€λ©΄, 각 λͺ¨λΈμ˜ 확신도λ₯Ό μ •λ°€ν•˜κ²Œ λ°˜μ˜ν•˜λŠ” Soft Voting (ν™•λ₯  가쀑 평균) 방식을 μ‚¬μš©ν•˜λŠ” 것이 κ°€μž₯ νš¨κ³Όμ μž…λ‹ˆλ‹€. κ°€μ€‘μΉ˜ w λŠ” μž„μ˜λ‘œ μ •ν•˜μ§€ μ•Šκ³  validation dataset μ—μ„œ grid search 둜 찾으며 (section 4.1), 찾은 값을 test dataset 의 가쀑합에 κ·ΈλŒ€λ‘œ μ μš©ν•©λ‹ˆλ‹€.

3. Principle

3.1 Weighted Soft Voting

두 λͺ¨λΈμ˜ ν™•λ₯ κ°’ $p_T$ κ³Ό $p_S$ 에 κ°€μ€‘μΉ˜ w ($0 \le w \le 1$) λ₯Ό μ μš©ν•˜μ—¬ ν•˜μ΄λΈŒλ¦¬λ“œ ν™•λ₯  $p_{\mathrm{hybrid}}$ λ₯Ό κ³„μ‚°ν•©λ‹ˆλ‹€.

$$p_{\mathrm{hybrid}} = w \cdot p_T + (1 - w) \cdot p_S \hspace{19em} (1)$$

이진 λΆ„λ₯˜μ˜ μ˜ˆμΈ‘κ°’ y_pred λŠ” μž„κ³„κ°’ 0.5 λ₯Ό κΈ°μ€€μœΌλ‘œ κ°ˆλ¦½λ‹ˆλ‹€.

$$y_{\mathrm{pred}} = \begin{cases} 1 & \mathrm{if}\ p_{\mathrm{hybrid}} \ge 0.5 \\\ 0 & \mathrm{otherwise} \end{cases} \hspace{15em} (2)$$

각 λͺ¨λΈμ΄ 내놓은 μ˜ˆμΈ‘κ°’μ€ 여기에 쓰이지 μ•ŠμŠ΅λ‹ˆλ‹€. y_pred λŠ” $p_{\mathrm{hybrid}}$ μ—μ„œ λ‹€μ‹œ 읽어내며, 각 λͺ¨λΈμ΄ κ·Έ μ•ˆμ—μ„œ μ°¨μ§€ν•˜λŠ” λͺ«μ€ κ°€μ€‘μΉ˜ w κ°€ μ •ν•©λ‹ˆλ‹€. 예츑 κ°’ 자체λ₯Ό ν•©μΉ˜λŠ” κ·œμΉ™μ€ κΌ­μ§€ 3.3 에 μžˆμŠ΅λ‹ˆλ‹€.

3.2 Multi-Class Extension

ν΄λž˜μŠ€κ°€ 3개 이상인 닀쀑 클래슀 λΆ„λ₯˜μ—μ„œλŠ” 각 ν΄λž˜μŠ€λ³„ ν™•λ₯  벑터 $p_T$ κ³Ό $p_S$ λ₯Ό κ°€μ€‘ν•©ν•œ ν›„ κ°€μž₯ 높은 ν™•λ₯ μ„ κ°€μ§„ 클래슀λ₯Ό y_pred 둜 μ‚ΌμŠ΅λ‹ˆλ‹€.

$$\mathbf{p}_{\mathrm{hybrid}} = w \cdot \mathbf{p}_T + (1 - w) \cdot \mathbf{p}_S \hspace{19em} (3)$$ $$y_{\mathrm{pred}} = \arg\max \left( \mathbf{p}_{\mathrm{hybrid}} \right) \hspace{19em} (4)$$

μž…λ ₯ 두 κ°œλŠ” λͺ¨λ‘ (N_samples, N_classes) ν˜•μƒμ˜ λ°°μ—΄μž…λ‹ˆλ‹€.

3.3 Single Predicted Value

각 λͺ¨λΈμ΄ 예츑 값을 ν•¨κ»˜ λ‚΄λ†“λŠ” 경우, 단일 μ˜ˆμΈ‘κ°’μ€ 두 값을 ν™•λ₯ λ‘œ 가쀑 ν‰κ· ν•œ κ²ƒμž…λ‹ˆλ‹€. 자기 닡을 더 ν™•μ‹ ν•˜λŠ” λͺ¨λΈ μͺ½μœΌλ‘œ κ²°κ³Όκ°€ λŒλ¦½λ‹ˆλ‹€.

$$v_{\mathrm{hybrid}} = \frac{w \cdot p_T \cdot v_T + (1 - w) \cdot p_S \cdot v_S}{w \cdot p_T + (1 - w) \cdot p_S} \hspace{15em} (5)$$

λΆ„λͺ¨λŠ” 식 (1) 의 ν•˜μ΄λΈŒλ¦¬λ“œ ν™•λ₯ μ΄λ―€λ‘œ, κΌ­μ§€ 3.1 의 Soft Voting 이 μ—¬κΈ°μ„œλ„ 두 값을 μ‹€μ–΄ λ‚˜λ¦…λ‹ˆλ‹€. κ΅¬ν˜„μ€ Appendix B.1 μž…λ‹ˆλ‹€. 가쀑합에 μ•žμ„œ 두 ν™•λ₯ μ΄ 0~1 μ•ˆμ— μžˆλŠ”μ§€ ν™•μΈν•˜λ©°, 두 ν™•λ₯ μ΄ λͺ¨λ‘ 0 인 ν–‰μ—μ„œλŠ” 값을 λŒλ €μ£ΌλŠ” λŒ€μ‹  였λ₯˜λ₯Ό λƒ…λ‹ˆλ‹€.

4. Optimal Weight Search

w 값을 μž„μ˜λ‘œ μ •ν•˜κΈ°λ³΄λ‹€λŠ”, Validation Datasetμ—μ„œ μ„±λŠ₯ μ§€ν‘œ (R-squared, ROC-AUC, F1-score λ“±) λ₯Ό κ°€μž₯ λ†’μ—¬μ£ΌλŠ” wλ₯Ό 탐색 (Grid Search) ν•˜μ—¬ μ„ μ •ν•˜λŠ” 것을 ꢌμž₯ν•©λ‹ˆλ‹€.

4.1 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 λ°μ΄ν„°μ…‹μ˜ 가쀑합 계산에 μ μš©ν•˜μ—¬ μ΅œμ’… 평가λ₯Ό μˆ˜ν–‰ν•˜λ©΄ λ©λ‹ˆλ‹€.

$$p_{\mathrm{hybrid,test}} = w_{\mathrm{best}} \cdot p_{T,\mathrm{test}} + (1 - w_{\mathrm{best}}) \cdot p_{S,\mathrm{test}} \hspace{19em} (6)$$

4.2 Metric Selection

μ§€ν‘œλŠ” 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)

r2_score

식 (5) 의 v_hybrid λ₯Ό y_true 와 λŒ‘λ‹ˆλ‹€. 이 λ¬Έμ„œμ˜ μ‚°μΆœλ¬Όμ΄ λ°”λ‘œ κ·Έ κ°’μž…λ‹ˆλ‹€.

  • μž₯점: λ…μžκ°€ κ°€μ Έκ°€λŠ” 값을 직접 겨λƒ₯. μž„κ³„κ°’μ„ μ •ν•  ν•„μš” μ—†μŒ. 연속값과 ν΄λž˜μŠ€μ— 같은 κ·œμΉ™μœΌλ‘œ 적용.
  • 단점: v_T, v_S κ°€ μžˆμ–΄μ•Ό 함. 두 ν™•λ₯ μ΄ λͺ¨λ‘ 0 인 ν–‰μ—μ„œλŠ” 식 (5) 의 λΆ„λͺ¨κ°€ 0 이라 μ •μ˜λ˜μ§€ μ•ŠμŒ. 였차λ₯Ό μ œκ³±ν•˜λ―€λ‘œ ν•œ ν–‰μ˜ 큰 μ˜€μ°¨κ°€ w λ₯Ό 쒌우.

mean_absolute_percentage_error

식 (5) 의 v_hybrid λ₯Ό y_true 와 λŒ€μ–΄, μ ˆλŒ€ 였차λ₯Ό μ •λ‹΅μœΌλ‘œ λ‚˜λˆˆ κ°’μ˜ 평균을 λƒ…λ‹ˆλ‹€.

  • μž₯점: λ°±λΆ„μœ¨λ‘œ μ½νžˆλ―€λ‘œ λ‹¨μœ„μ™€ 크기가 λ‹€λ₯Έ λŒ€μƒλΌλ¦¬ κ²°κ³Όλ₯Ό 견쀄 수 있음. 정닡이 큰 행이 μ§€ν‘œλ₯Ό λ…μ°¨μ§€ν•˜μ§€ μ•ŠμŒ.
  • 단점: 정닡이 0 μ΄κ±°λ‚˜ 0 에 κ°€κΉŒμš°λ©΄ λ°œμ‚°. 같은 크기라도 κ³ΌλŒ€μ˜ˆμΈ‘μ˜ 벌점이 κ³Όμ†Œμ˜ˆμΈ‘λ³΄λ‹€ 큼.

ThresholdMetric(f1_score)

threshold κ°€ λ§Œλ“  클래슀 y_pred λ₯Ό 정밀도와 μž¬ν˜„μœ¨μ˜ μ‘°ν™” ν‰κ· μœΌλ‘œ μž½λ‹ˆλ‹€.

  • μž₯점: λ ˆμ΄λΈ”μ΄ λΆˆκ· ν˜•μΌ λ•Œ μ–‘μ„± 클래슀의 μ„±λŠ₯이 λ“œλŸ¬λ‚¨. μ‹€μ œλ‘œ μ“°λŠ” λ™μž‘μ μ—μ„œμ˜ μ„±λŠ₯을 ν•œ 숫자둜 읽음.
  • 단점: ThresholdMetric 이 μ₯” μž„κ³„κ°’μ— λ¬Άμ—¬ μžˆμ–΄ μž„κ³„κ°’μ΄ λ°”λ€Œλ©΄ κ³ λ₯Έ w κ°€ λ‚‘μŒ. μŒμ„± ν΄λž˜μŠ€λŠ” 그것이 λΆ€λ₯Έ 였λ₯˜λ‘œλ§Œ 반영.

ThresholdMetric(accuracy_score)

threshold κ°€ λ§Œλ“  클래슀 y_pred κ°€μš΄λ° 맞힌 ν–‰μ˜ λΉ„μœ¨μž…λ‹ˆλ‹€.

  • μž₯점: κ²°κ³Όλ₯Ό κ°€μž₯ λ‹¨μˆœν•˜κ²Œ μ½λŠ” 방식. 두 클래슀λ₯Ό 같은 무게둜 μ…ˆ.
  • 단점: λ ˆμ΄λΈ”μ΄ λΆˆκ· ν˜•μ΄λ©΄ λ‹€μˆ˜ 클래슀만 λ§žν˜€λ„ λ†’κ²Œ λ‚˜μ˜΄. f1_score 와 같은 λ°©μ‹μœΌλ‘œ μž„κ³„κ°’μ— λ¬Άμž„.

roc_auc_score

식 (1) 의 p_hybrid κ°€ λ§Œλ“œλŠ” μˆœμœ„λ₯Ό λͺ¨λ“  μž„κ³„κ°’μ— 걸쳐 ν•œκΊΌλ²ˆμ— μž½λ‹ˆλ‹€.

  • μž₯점: μž„κ³„κ°’μ„ μ •ν•  ν•„μš”κ°€ μ—†μ–΄ λ™μž‘μ μ„ μ •ν•˜κΈ° μ „μ˜ 탐색에 맞음. λ ˆμ΄λΈ” λΆˆκ· ν˜•μ— 견고.
  • 단점: ν™•λ₯ μ„ 단쑰 λ³€ν™˜ν•΄λ„ 값이 κ·ΈλŒ€λ‘œλΌ calibration 이 μ–΄κΈ‹λ‚œ λͺ¨λΈλ„ 톡과. 단일 μ˜ˆμΈ‘κ°’μ„ μž¬λŠ” μ§€ν‘œκ°€ μ•„λ‹˜.

log_loss

식 (1) 의 p_hybrid λ₯Ό y_true 와 λŒ€μ–΄, ν™•λ₯ μ΄ μ •λ‹΅μ—μ„œ μ–Όλ§ˆλ‚˜ λ–¨μ–΄μ Έ μžˆλŠ”μ§€λ‘œ λ²Œμ μ„ λ§€κΉλ‹ˆλ‹€.

  • μž₯점: ν™•λ₯ μ˜ λˆˆκΈˆκΉŒμ§€ μ±„μ ν•˜λŠ” μœ μΌν•œ μ§€ν‘œλΌ, κΌ­μ§€ 5 κ°€ κ²½κ³ ν•˜λŠ” calibration μƒνƒœκ°€ λ“œλŸ¬λ‚¨.
  • 단점: 확신을 κ°–κ³  ν‹€λ¦° ν•œ ν–‰μ˜ 벌점이 맀우 μ»€μ„œ κ·Έ 행이 w λ₯Ό 쒌우. ν™•λ₯ μ΄ 0 μ΄λ‚˜ 1 이면 클리핑 μ—†μ΄λŠ” λ°œμ‚°.

5. Cautions

두 λͺ¨λΈμ˜ ν™•λ₯  뢄포가 μ •κ΅ν•˜κ²Œ λ§žμΆ”μ–΄μ Έ μžˆλŠ”μ§€ 확인해야 ν•©λ‹ˆλ‹€. ν•œ λͺ¨λΈμ΄ ν™•λ₯ μ„ λ„ˆλ¬΄ κ³Όμ‹  (예: λŒ€λΆ€λΆ„ 0.05 λ˜λŠ” 0.95 근처) ν•˜κ³  λ‹€λ₯Έ λͺ¨λΈμ€ μ‹ μ€‘ν•œ 경우 (예: 0.4∼0.6 사이), λ‹¨μˆœ κ°€μ€‘μΉ˜ μ‘°ν•© μ‹œ κ³Όμ‹ ν•˜λŠ” λͺ¨λΈμ˜ 영ν–₯λ ₯이 κ³Όλ„ν•˜κ²Œ 컀질 수 μžˆμŠ΅λ‹ˆλ‹€.

6. Further Work

  • ν™•λ₯  calibration 적용
    • 무엇: IsotonicRegressionμ΄λ‚˜ Platt Scaling을 ν†΅ν•œ calibration 을 두 λͺ¨λΈμ˜ ν™•λ₯ μ— μ μš©ν•œ λ’€ 가쀑합.
    • μ™œ μ§€κΈˆ: κΌ­μ§€ 5 의 쑰건, 즉 ν•œ λͺ¨λΈμ΄ κ³Όμ‹ ν•˜κ³  λ‹€λ₯Έ λͺ¨λΈμ΄ μ‹ μ€‘ν•œ μƒνƒœμ—μ„œλŠ” κ°€μ€‘μΉ˜λ§ŒμœΌλ‘œ 영ν–₯λ ₯의 λΆˆκ· ν˜•μ„ λ°”λ‘œμž‘μ§€ λͺ»ν•¨.
    • 무엇이 ν•„μš”: Calibration 에 μ“Έ 데이터와, calibration μ „ν›„μ˜ 졜적 w 및 μ§€ν‘œ 점수 비ꡐ.

References

N/A β€” μ™ΈλΆ€ 좜처λ₯Ό μΈμš©ν•˜μ§€ μ•ŠμŒ.


Appendix A. Terminology

  • 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. ν™•λ₯ μ„ λ°”λ‘œ λ°›λŠ” μ§€ν‘œλ“€κ³Ό 같은 λ°©μ‹μœΌλ‘œ ν™•λ₯ μ„ μ±„μ ν•œλ‹€.

Appendix B. Python Implementation

B.1 Single Predicted Value

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) / denominator

B.2 Optimal Weight Search

from 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

B.3 Execution Example

# --- 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.    ]

Our Score
Click to rate this post!
[Total: 1 Average: 4]
Visited 16 times, 1 visit(s) today

Leave a Comment

Your email address will not be published. Required fields are marked *