spearman_rho_score#
- sklr.metrics.spearman_rho_score(y_true: ArrayLike, y_pred: ArrayLike, *, sample_weight: ArrayLike | None = None) float#
Compute Spearman’s \(\rho\) between label rankings.
Spearman’s rank correlation coefficient \(\rho\) [spearman_proof_1904] is the product-moment correlation between the positions that two rankings of the same labels give to each label, which only depends on the sum of the squared differences between them. It ranges from
-1, when one ranking is the reverse of the other, to1, when both rankings are equal. The score of the rankings is the average of the coefficients of their samples.Read more in the User Guide.
- Parameters:
- y_truearray-like of shape (n_samples, n_labels)
The true rankings, complete and without ties, as described in Ranking representation.
- y_predarray-like of shape (n_samples, n_labels)
The predicted rankings, complete and without ties.
- sample_weightarray-like of shape (n_samples,), default=None
Non-negative weights of the samples in the average. If
None, the samples are equally weighted.
- Returns:
- scorefloat
The average Spearman’s \(\rho\) of the samples, between
-1and1.
See also
kendall_tau_scoreCompute Kendall’s \(\tau\) between label rankings.
scipy.stats.spearmanrSpearman’s \(\rho\) between two variables.
Notes
Given a ranking \(\pi\) of the labels \(y_1, \dots, y_n\), where \(\pi(i)\) is the position of \(y_i\), Spearman’s \(\rho\) between the predicted ranking \(\hat{\pi}\) and the true ranking \(\sigma\) is the product-moment correlation of their positions, with the deviations taken from their median [spearman_proof_1904], which is \(m = (n + 1) / 2\) for both rankings:
\[\rho(\hat{\pi}, \sigma) = \frac{\sum_{i=1}^n (\hat{\pi}(i) - m) (\sigma(i) - m)}{\sqrt{\sum_{i=1}^n (\hat{\pi}(i) - m)^2 \sum_{i=1}^n (\sigma(i) - m)^2}}.\]Without ties, both sums of squares are \(n(n^2 - 1) / 12\), and the sum of the products is that value minus half the sum of the squared differences of the positions, so
\[\rho(\hat{\pi}, \sigma) = 1 - \frac{6 \sum_{i=1}^n (\hat{\pi}(i) - \sigma(i))^2}{n(n^2 - 1)},\]which is how it is computed. It is equal to the coefficient computed by
scipy.stats.spearmanr(). Rankings with ties are rejected, because the second formula only holds without them.References
Examples
>>> from sklr.metrics import spearman_rho_score >>> y_true = [[1, 2, 3], [3, 2, 1]] >>> y_pred = [[1, 2, 3], [1, 3, 2]] >>> spearman_rho_score(y_true, y_pred) 0.25 >>> spearman_rho_score(y_true, y_pred, sample_weight=[3, 1]) 0.625