Classifier Metrics
classifier_metrics.nr72 lines
classifier_metrics.nr· neuro
// Evaluating a linear classifier over batches of any size. Integration example: `.argmax` for
// the predicted class, element-wise `==` against the labels and `.cast::<i32>()` to count the
// hits, a numerically stable softmax built from `.max(axis:, keep: true)`, `.exp()` and
// `.sum(axis:, keep: true)`, a `?B` batch bound at a call and carried through `@`, a struct
// holding the weights, and a `Float`-generic loss.
struct Classifier {
weights: Tensor<f32, [3, 4]>,
}
impl Classifier {
func logits(&self, x: &Tensor<f32, [?B, 3]>) -> Tensor<f32, [?B, 4]> {
x @ &self.weights
}
// The maximum of each row is subtracted before `.exp()`, so no exponent is positive and
// nothing overflows; the kept axis broadcasts the row values back across the row.
func probabilities(&self, x: &Tensor<f32, [?B, 3]>) -> Tensor<f32, [?B, 4]> {
val logits = self.logits(x)
val scaled = (&logits - (&logits).max(axis: 1, keep: true)).exp()
&scaled / (&scaled).sum(axis: 1, keep: true)
}
}
// The mean of `-log p` at each row's label, read element by element.
func cross_entropy<T: Float>(p: &Tensor<T, [?B, 4]>, labels: &Tensor<i32, [?B]>) -> T {
mut total = T::zero()
for i in 0..B {
total += -(p[i, labels[i] as u64].log())
}
total / T::from_f64(B as f64)
}
func batch(n: u64) -> (Tensor<f32, [?, 3]>, Tensor<i32, [?]>) {
mut x = Tensor::<f32, [?, 3]>::zeros(dims: [n])
mut y = Tensor::<i32, [?]>::zeros(dims: [n])
for i in 0..n {
x[i, i % 3] = 1.0 + (i / 3) as f32
x[i, (i + 1) % 3] = 0.5
// Every fourth label is wrong on purpose, so accuracy is not perfect.
y[i] = match i % 4 {
3 => 3,
_ => (i % 3) as i32,
}
}
(x, y)
}
// One call binds `B` from `x`, and `y` is checked against it, so the predictions and the
// labels share their axis and compare element-wise.
func evaluate(model: &Classifier, x: &Tensor<f32, [?B, 3]>, y: &Tensor<i32, [?B]>) -> i32 {
val predicted = model.logits(x).argmax(axis: 1)
val hits = (&predicted == y).cast::<i32>()
val p = model.probabilities(x)
val loss = cross_entropy(&p, y)
val rows_sum = (&p).sum(axis: 1)
val correct = hits.sum()
println("batch of {B}: {correct} correct, first prediction {predicted[0]}, loss {loss}, row sum {rows_sum[0]}")
correct
}
func main() -> i32 {
val model = Classifier {
weights: [[2.0, 0.0, 0.0, -1.0], [0.0, 2.0, 0.0, -1.0], [0.0, 0.0, 2.0, -1.0]],
}
mut correct: i32 = 0
for n in [4u64, 9u64] {
val (x, y) = batch(n)
correct += evaluate(&model, &x, &y)
}
correct
}
neuroc run classifier_metrics.nr
batch of 4: 3 correct, first prediction 0, loss 1.962444067001343, row sum 1.0
batch of 9: 7 correct, first prediction 0, loss 1.945789098739624, row sum 1.0