precision_n_scores can report up to 1.0 (or down to 0.0) when scores tie at the rank-n cutoff: get_label_n flags fewer than n rows
pyod/utils/utility.py:274-275 (in get_label_n, called from precision_n_scores at :222, returned at :228):
threshold = percentile(y_pred, 100 * (1 - outliers_fraction))
y_pred = (y_pred > threshold).astype('int')
...
return precision_score(y, y_pred)With distinct scores the interpolated percentile falls strictly between the n-th and (n+1)-th ranked score, so exactly n rows are flagged and the result is Precision@n. When scores tie at the cutoff, the percentile lands on the tied value and the strict > drops the whole tied block. Fewer than n rows are flagged, and precision_score divides by that smaller count.
The get_label_n docstring says it assigns 1 to the top n outlier scores. In #2 the contract is stated directly: get_label_n(y_true, y_train_scores) "will return a binary label which contains exactly the same number of outliers as y_true". The same thread gives precision @ k as the other name for the metric, which divides by k.
Measured
get_label_n and precision_n_scores were extracted from the file with ast and run on their own, without importing pyod, against the real numpy.percentile, sklearn.metrics.precision_score, column_or_1d and check_consistent_length. They were run on numpy 1.26.4 with scikit-learn 1.4.2, and on numpy 2.3.1 with scikit-learn 1.7.0, and gave identical results. "Tie-aware" is the expected P@n when ties are broken at random, which is the same as dividing by n. For the first row, a 20,000-trial random tie-break simulation gives 0.2321.
| case | n | rows flagged | reported | tie-aware P@n |
|---|---|---|---|---|
| one outlier on top, other 99 scores identical | 5 | 1 | 1.0000 | 0.2323 |
| coarse: 3 outliers on top, 97 tied | 10 | 3 | 1.0000 | 0.3505 |
| fine: distinct scores, 5 of top 10 correct | 10 | 10 | 0.5000 | 0.5000 |
| histogram-style: 4 outliers at 3.0, 20 tied at 2.0 (6 out, 14 in) | 10 | 4 | 1.0000 | 0.5800 |
| 15 tied at the max (all 10 outliers + 5 inliers) | 10 | 0 | 0.0000 | 0.6667 |
n=3 passed explicitly, one on top, 9 tied |
3 | 1 | 1.0000 | 0.4815 |
| constant scores (control) | 10 | 0 | 0.0000 | 0.1000 |
| inverted ranking, distinct (control) | 10 | 10 | 0.0000 | 0.0000 |
| perfect ranking, distinct (control) | 10 | 10 | 1.0000 | 1.0000 |
| 6 of top 10 correct, distinct (control) | 10 | 10 | 0.6000 | 0.6000 |
TestMetrics fixture in test_utility.py |
4 | 4 | 0.5000 | 0.5000 |
Distinct scores give the right value. So does the existing test fixture, which has no tie at the cutoff. Once there is a tie at the cutoff, the result can be too high (up to 1.0) or too low (down to 0.0).
Consequence
A detector that gives one point a high score and every other point the same score reports a perfect precision @ rank n. Detectors with discrete or plateaued scores are the ones exposed: HBOS on few or coarse features, and the subsequence detectors whose "broad tied score plateaus" are described in #739. In the coarse vs fine rows above, the ranking between two detectors is inverted: 1.0 vs 0.5 reported, 0.35 vs 0.5 tie-aware.
The same number is printed by evaluate_print (pyod/utils/data.py:346), returned by fit_predict_score(..., scoring='prc_n_score') (pyod/models/base.py:527, deprecated since 0.6.9 but still present; pyod/models/xgbod.py:450) and written to the benchmark table (notebooks/benchmark.py:263).
The detection_lift proposed in #739 divides this value by prevalence, and its shared test helper accepts a detector when the rounded scores are not constant and the lift is above 2.7. Take 100 samples with 10 outliers, one outlier scored 1.0 and the other 99 rows tied at 0.0. That detector has 2 unique scores and a reported P@n of 1.0, so its lift is 10.0 and it passes. Its tie-aware P@n is 0.1818, a lift of 1.82, which is below the bound. #736/#739 cover the chance level and the constant-score case but not ties. The same percentile-then-> pattern is used by score_to_label (utility.py:195-196). #135 reports the analogous effect on detector labels (far fewer outliers flagged than the contamination asked for), which was attributed to tied scores.
Suggested fix
Make the denominator n and handle the tied block explicitly. ad_engine.py:764 already selects exactly top_k rows (np.argsort(scores)[::-1][:top_k]). But breaking ties by index order is biased, because generate_data appends the outliers last (data.py:73-75). The tie-aware expectation avoids that:
def precision_n_scores(y, y_pred, n=None):
y = column_or_1d(y)
y_pred = column_or_1d(y_pred)
check_consistent_length(y, y_pred)
n = int(np.count_nonzero(y)) if n is None else int(n)
if n == 0:
return 0.0
cut = np.sort(y_pred)[-n] # score of the n-th ranked row
above = y_pred > cut
tied = y_pred == cut
slots = n - above.sum() # rank positions left for the tied block
hits = y[above].sum() + slots * y[tied].mean()
return float(hits / n)On the table above this returns the tie-aware column exactly. Every distinct-score case is unchanged, including the existing TestMetrics fixture. One behaviour does change: when the whole top block is tied, including constant scores, the result becomes the tie-aware value instead of 0.0. A constant-score detector then reports the prevalence, a lift of 1.0, instead of 0.0. A regression test using the first row ([0.0]*99 + [1.0] with 5 outliers, the top-scored row an outlier) would catch it.
get_label_n should either document that ties can flag fewer than n rows or apply an explicit tie rule. argmaxn (utility.py:347) is not a model for this. It selects with >= and returns the whole tied block, so on the first row with n=5 it returns all 100 indices.
Source: yzhao062/pyod