Tensor Casts Positions
tensor_casts_positions.nr39 lines
tensor_casts_positions.nr· neuro
// Element casts, kept axes and positions. `.cast::<U>()` converts every element the way `as`
// converts a scalar: integers to floats exactly where they fit, floats to integers truncated
// toward zero and saturated at the type's ends, a mask's `bool`s to `0` and `1`. A reduction
// along an axis with `keep: true` leaves that axis at extent 1, the shape that broadcasts
// back against its input. `.argmax(axis:)` and `.argmin(axis:)` give the position of the
// extreme along an axis as an `i32`, the lowest one at a tie.
func main() -> i32 {
val logits: Tensor<f32, [3, 4]> = [[0.5, 2.0, -1.0, 2.0], [3.5, 0.0, 1.0, -2.0], [0.0, 0.25, 4.0, 1.5]]
val labels: Tensor<i32, [3]> = [1, 0, 3]
// The borrow is read and stays usable; an owned receiver would be consumed.
val rounded = (&logits).cast::<i32>()
println("rounded: {rounded[0, 0]} {rounded[1, 0]} {rounded[2, 3]}")
// Saturation and NaN follow `as`: out-of-range values clamp, NaN becomes 0.
val wide: Tensor<f64, [3]> = [300.0, -5.0, 0.0 / 0.0]
val bytes = wide.cast::<u8>()
println("bytes: {bytes[0]} {bytes[1]} {bytes[2]}")
// Row 0 has its maximum twice, and the earlier position wins.
val predicted = (&logits).argmax(axis: 1)
val coldest = (&logits).argmin(axis: -1)
println("predicted: {predicted[0]} {predicted[1]} {predicted[2]}, coldest: {coldest[0]} {coldest[1]} {coldest[2]}")
// Accuracy: compare positions with labels, then read the mask as numbers. A `bool`
// converts to an integer only, as with `as`, so a float mean goes through one.
val hits = (&predicted == &labels).cast::<i32>()
println("hits: {hits[0]} {hits[1]} {hits[2]}")
println("accuracy: {hits.cast::<f32>().mean()}")
// Subtracting each row's maximum keeps every value at or below zero, the usual guard
// before `.exp()`.
val shifted = &logits - (&logits).max(axis: 1, keep: true)
val scaled = shifted.exp()
val probabilities = &scaled / (&scaled).sum(axis: 1, keep: true)
println("row 1: {probabilities[1, 0]} {probabilities[1, 3]}")
predicted.sum() + coldest.sum()
}
neuroc run tensor_casts_positions.nr
rounded: 0 3 1
bytes: 255 0 0
predicted: 1 0 2, coldest: 2 3 0
hits: 1 1 0
accuracy: 0.6666666865348816
row 1: 0.8957610726356506 0.003660770831629634