1mod classification;
4mod confusion;
5mod curves;
6mod perplexity;
7mod regression;
8mod topk;
9mod weighted;
10
11pub use classification::AccuracyCount;
12pub use confusion::ConfusionCounts;
13pub use curves::StreamingBinaryCurves;
14pub use perplexity::Perplexity;
15pub use regression::RegressionErrors;
16pub use topk::TopKAccuracy;
17pub use weighted::WeightedMean;
18
19use crate::{DType, Error, Matrix, Result, matrix};
20
21pub fn scalar_loss(loss: &Matrix) -> Result<f32> {
31 if loss.dtype() != DType::F32 || loss.num_elements() != 1 {
32 return Err(Error::invalid_argument(format!(
33 "ml scalar_loss requires exactly one F32 value; found shape {:?} {}",
34 loss.shape(),
35 loss.dtype().token()
36 )));
37 }
38 Ok(loss.read_f32()?[0])
39}
40
41pub fn accuracy(logits: &Matrix, labels: &Matrix) -> Result<f32> {
52 let count = matrix::categorical_accuracy_count(logits, labels)?;
53 let correct = count.read::<u32>()?[0];
54 Ok(correct as f32 / labels.num_elements() as f32)
55}
56
57pub fn precision_recall_f1(
72 logits: &Matrix,
73 labels: &Matrix,
74 class_index: usize,
75) -> Result<ClassificationCounts> {
76 let &[samples, num_classes] = logits.shape() else {
77 return Err(Error::invalid_argument(format!(
78 "metric logits must be rank two; found {:?}",
79 logits.shape(),
80 )));
81 };
82 if logits.dtype() != DType::F32 {
83 return Err(Error::invalid_argument(format!(
84 "metric logits must be F32; found {}",
85 logits.dtype().token(),
86 )));
87 }
88 if class_index >= num_classes {
89 return Err(Error::invalid_argument(format!(
90 "class index {class_index} exceeds the class axis {num_classes}"
91 )));
92 }
93 if labels.num_elements() != samples {
94 return Err(Error::invalid_argument(format!(
95 "metric logits predict {samples} rows; found {} labels",
96 labels.num_elements(),
97 )));
98 }
99 let logits_flat = logits.read_f32()?;
100 let labels_flat = labels.read::<u32>()?;
101 let mut counts = ClassificationCounts::default();
102 for (row, label) in labels_flat.iter().enumerate() {
103 let prediction = logits_flat[row * num_classes..(row + 1) * num_classes]
104 .iter()
105 .enumerate()
106 .max_by(|a, b| a.1.total_cmp(b.1).then(b.0.cmp(&a.0)))
107 .map(|(index, _)| index)
108 .unwrap_or(0);
109 let predicted_class = prediction == class_index;
110 let actual_class = *label as usize == class_index;
111 match (predicted_class, actual_class) {
112 (true, true) => counts.true_positives += 1,
113 (true, false) => counts.false_positives += 1,
114 (false, true) => counts.false_negatives += 1,
115 (false, false) => counts.true_negatives += 1,
116 }
117 }
118 Ok(counts)
119}
120
121#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
123pub struct ClassificationCounts {
124 pub true_positives: u64,
125 pub false_positives: u64,
126 pub true_negatives: u64,
127 pub false_negatives: u64,
128}
129
130impl ClassificationCounts {
131 pub fn precision(&self) -> f32 {
133 let predicted = self.true_positives + self.false_positives;
134 if predicted == 0 {
135 return 0.0;
136 }
137 self.true_positives as f32 / predicted as f32
138 }
139
140 pub fn recall(&self) -> f32 {
142 let actual = self.true_positives + self.false_negatives;
143 if actual == 0 {
144 return 0.0;
145 }
146 self.true_positives as f32 / actual as f32
147 }
148
149 pub fn f1(&self) -> f32 {
151 let (p, r) = (self.precision(), self.recall());
152 if p + r == 0.0 {
153 return 0.0;
154 }
155 2.0 * p * r / (p + r)
156 }
157}
158
159pub fn macro_f1(logits: &Matrix, labels: &Matrix, num_classes: usize) -> Result<f32> {
165 if num_classes == 0 {
166 return Err(Error::invalid_argument(
167 "macro_f1 requires at least one class",
168 ));
169 }
170 let mut total = 0.0;
171 for class_index in 0..num_classes {
172 total += precision_recall_f1(logits, labels, class_index)?.f1();
173 }
174 Ok(total / num_classes as f32)
175}
176
177pub fn roc_auc(scores: &Matrix, labels: &Matrix) -> Result<f32> {
189 if scores.dtype() != DType::F32 {
190 return Err(Error::invalid_argument(format!(
191 "roc_auc requires F32 scores; found {}",
192 scores.dtype().token()
193 )));
194 }
195 let scores = scores.read_f32()?;
196 let labels = labels.read::<u32>()?;
197 if scores.len() != labels.len() {
198 return Err(Error::invalid_argument(format!(
199 "roc_auc has {} scores for {} labels",
200 scores.len(),
201 labels.len(),
202 )));
203 }
204 if scores.is_empty() || labels.iter().any(|label| *label > 1) {
205 return Err(Error::invalid_argument(
206 "roc_auc requires a nonempty binary label set",
207 ));
208 }
209 let positives = labels.iter().filter(|label| **label == 1).count();
210 if positives == 0 || positives == labels.len() {
211 return Err(Error::invalid_argument(
212 "roc_auc requires at least one positive and one negative label",
213 ));
214 }
215 let mut order: Vec<usize> = (0..scores.len()).collect();
217 order.sort_by(|a, b| scores[*a].total_cmp(&scores[*b]));
218 let mut rank_sum_positive = 0.0_f64;
219 let mut index = 0;
220 while index < order.len() {
221 let mut end = index + 1;
222 while end < order.len() && scores[order[end]] == scores[order[index]] {
223 end += 1;
224 }
225 let average_rank = (index + 1 + end) as f64 / 2.0;
226 for &sample in &order[index..end] {
227 if labels[sample] == 1 {
228 rank_sum_positive += average_rank;
229 }
230 }
231 index = end;
232 }
233 let negatives = (labels.len() - positives) as f64;
234 let positives = positives as f64;
235 Ok(((rank_sum_positive - positives * (positives + 1.0) / 2.0) / (positives * negatives)) as f32)
236}
237
238pub fn pr_auc(scores: &Matrix, labels: &Matrix) -> Result<f32> {
251 if scores.dtype() != DType::F32 {
252 return Err(Error::invalid_argument(format!(
253 "pr_auc requires F32 scores; found {}",
254 scores.dtype().token()
255 )));
256 }
257 let scores = scores.read_f32()?;
258 let labels = labels.read::<u32>()?;
259 if scores.len() != labels.len() {
260 return Err(Error::invalid_argument(format!(
261 "pr_auc has {} scores for {} labels",
262 scores.len(),
263 labels.len()
264 )));
265 }
266 if scores.is_empty()
267 || scores.iter().any(|score| !score.is_finite())
268 || labels.iter().any(|label| *label > 1)
269 {
270 return Err(Error::invalid_argument(
271 "pr_auc requires finite scores and a nonempty binary label set",
272 ));
273 }
274 let total_positives = labels.iter().filter(|label| **label == 1).count();
275 if total_positives == 0 {
276 return Err(Error::invalid_argument(
277 "pr_auc requires at least one positive label",
278 ));
279 }
280 let mut order: Vec<usize> = (0..scores.len()).collect();
281 order.sort_by(|a, b| scores[*b].total_cmp(&scores[*a]));
282 let total_pos = total_positives as f64;
283 let mut tp = 0.0_f64;
284 let mut fp = 0.0_f64;
285 let mut prev_recall = 0.0_f64;
286 let mut ap = 0.0_f64;
287 let mut index = 0;
288 while index < order.len() {
289 let mut end = index + 1;
290 while end < order.len() && scores[order[end]] == scores[order[index]] {
291 end += 1;
292 }
293 for &sample in &order[index..end] {
294 if labels[sample] == 1 {
295 tp += 1.0;
296 } else {
297 fp += 1.0;
298 }
299 }
300 let recall = tp / total_pos;
301 let precision = tp / (tp + fp);
302 ap += (recall - prev_recall) * precision;
303 prev_recall = recall;
304 index = end;
305 }
306 Ok(ap as f32)
307}
308
309pub fn bleu(references: &[Vec<u32>], hypotheses: &[Vec<u32>], max_order: usize) -> Result<f32> {
322 use std::collections::HashMap;
323 if max_order == 0 {
324 return Err(Error::invalid_argument("bleu requires max_order >= 1"));
325 }
326 if references.len() != hypotheses.len() {
327 return Err(Error::invalid_argument(format!(
328 "bleu received {} references for {} hypotheses",
329 references.len(),
330 hypotheses.len(),
331 )));
332 }
333 if hypotheses.iter().any(Vec::is_empty) {
334 return Err(Error::invalid_argument("bleu hypotheses must be nonempty"));
335 }
336 let ngrams = |sequence: &[u32], order: usize| -> HashMap<Vec<u32>, u64> {
337 let mut counts = HashMap::new();
338 for window in sequence.windows(order) {
339 *counts.entry(window.to_vec()).or_insert(0) += 1;
340 }
341 counts
342 };
343 let mut matches = vec![0_u64; max_order];
344 let mut candidates = vec![0_u64; max_order];
345 let (mut ref_len, mut hyp_len) = (0_u64, 0_u64);
346 for (reference, hypothesis) in references.iter().zip(hypotheses.iter()) {
347 ref_len += reference.len() as u64;
348 hyp_len += hypothesis.len() as u64;
349 for (order, (matched, total)) in
350 (1..=max_order).zip(matches.iter_mut().zip(candidates.iter_mut()))
351 {
352 if hypothesis.len() < order {
353 continue;
354 }
355 let reference_counts = ngrams(reference, order);
356 *total += (hypothesis.len() + 1 - order) as u64;
357 for (gram, count) in ngrams(hypothesis, order) {
358 *matched += count.min(reference_counts.get(&gram).copied().unwrap_or(0));
359 }
360 }
361 }
362 if candidates.contains(&0) {
363 return Err(Error::invalid_argument(
364 "bleu requires every hypothesis to cover every n-gram order",
365 ));
366 }
367 if matches.contains(&0) {
368 return Ok(0.0);
369 }
370 let log_precision: f64 = matches
371 .iter()
372 .zip(candidates.iter())
373 .map(|(matched, total)| (*matched as f64 / *total as f64).ln())
374 .sum::<f64>()
375 / max_order as f64;
376 let brevity = if hyp_len >= ref_len {
377 1.0
378 } else {
379 (1.0 - ref_len as f64 / hyp_len as f64).exp()
380 };
381 Ok((brevity * log_precision.exp()) as f32)
382}