use super::classification::AccuracyCount;
use crate::{Error, Matrix, Result};
pub struct TopKAccuracy {
k: usize,
counts: AccuracyCount,
}
impl TopKAccuracy {
#[inline]
#[must_use]
pub fn new(k: usize) -> Self {
Self {
k: k.max(1),
counts: AccuracyCount::new(),
}
}
#[must_use]
pub const fn k(&self) -> usize {
self.k
}
pub fn update_device(&mut self, logits: &Matrix, labels: &Matrix) -> Result<()> {
let shape = logits.shape();
if shape.len() != 2 || labels.shape() != [shape[0]] {
return Err(Error::invalid_argument(format!(
"top-{} accuracy requires [N, C] logits and [N] labels; found {:?} and {:?}",
self.k,
shape,
labels.shape()
)));
}
let rows = shape[0];
let classes = shape[1];
if rows == 0 || classes == 0 {
return Err(Error::invalid_argument(
"top-k accuracy requires nonempty batches",
));
}
let logits_host = logits.read_f32()?;
let labels_host = labels.read::<u32>()?;
let mut correct = 0_u64;
for (row, &label) in labels_host.iter().enumerate() {
let label = label as usize;
if label >= classes {
return Err(Error::invalid_argument(format!(
"top-k accuracy label {label} exceeds the {classes} classes"
)));
}
let base = row * classes;
let row_logits = &logits_host[base..base + classes];
let label_score = row_logits[label];
let strictly_above = row_logits
.iter()
.filter(|&&value| value > label_score)
.count();
if strictly_above < self.k {
correct += 1;
}
}
self.counts.update(correct, rows as u64);
Ok(())
}
pub fn merge(&mut self, other: &mut Self) -> Result<()> {
if self.k != other.k {
return Err(Error::invalid_argument(format!(
"cannot merge top-{} accuracy with top-{} accuracy",
self.k, other.k
)));
}
self.counts.merge(&mut other.counts);
Ok(())
}
pub fn result(&mut self) -> Result<f64> {
self.counts.result()
}
#[must_use]
pub const fn samples(&self) -> u64 {
self.counts.counts().1
}
pub fn reset(&mut self) {
self.counts.reset();
}
}