Holdout Split
holdout_split.nr36 lines
holdout_split.nr· neuro
// A linear classifier scored on a held-out split. Integration example: a bias column joined
// onto the features with `Tensor::concat`, the rows cut into training and held-out parts with
// `.split_at`, an `@` forward pass, `.argmax` predictions counted through `.cast::<i32>()`, a
// generic accuracy over any row count `N`, and the two parts' accuracies set side by side with
// `Tensor::stack`. The exit code is the number of held-out rows classified correctly.
// Fraction of rows whose highest score sits at the label.
func accuracy<N>(scores: &Tensor<f32, [N, 3]>, labels: &Tensor<i32, [N]>) -> Tensor<f32, [1]> {
val hits = (scores.argmax(axis: 1) == labels).cast::<i32>().cast::<f32>()
hits.mean(axis: 0, keep: true)
}
func main() -> i32 {
val features: Tensor<f32, [6, 2]> = [[2.0, 0.0], [0.0, 2.0], [-1.0, -1.0], [3.0, 1.0], [1.0, 3.0], [0.5, 0.5]]
val labels: Tensor<i32, [6]> = [0, 1, 2, 0, 1, 1]
// A constant 1 in a third column lets the last weight row act as a bias.
val ones: Tensor<f32, [6, 1]> = Tensor::ones()
val inputs = Tensor::concat([&features, &ones], axis: 1)
val weights: Tensor<f32, [3, 3]> = [[1.0, 0.0, -1.0], [0.0, 1.0, -1.0], [0.0, 0.0, 0.5]]
// The first four rows train, the last two are held out; the labels split the same way.
val (train, held) = (&inputs).split_at(axis: 0, at: 4)
val (train_labels, held_labels) = labels.split_at(axis: 0, at: 4)
val train_scores = &train @ &weights
val held_scores = &held @ &weights
// Row 5 is [0.5, 0.5, 1] with scores 0.5, 0.5 and -0.5: a tie goes to class 0, so
// the held-out part gets one of its two rows wrong.
val both = Tensor::stack([accuracy(&train_scores, &train_labels), accuracy(&held_scores, &held_labels)], axis: 0)
println("inputs: {inputs[2, 2]} {inputs.sum()}")
println("train: {both[0, 0]}, held out: {both[1, 0]}")
val correct = ((&held_scores).argmax(axis: 1) == &held_labels).count()
correct as i32
}
neuroc run holdout_split.nr
inputs: 1.0 17.0
train: 1.0, held out: 0.5