Tensor Join
tensor_join.nr49 lines
tensor_join.nr· neuro
// Joining and splitting tensors. `Tensor::concat([parts], axis:)` lays its parts end to end
// along an axis they share; the other axes must agree. `Tensor::stack([parts], axis:)` puts
// equal-shaped parts side by side along a new axis, inserted at that position of the result.
// `.split_at(axis:, at:)` cuts one tensor in two at a constant position and returns the
// halves as a pair. Over extent parameters the joined extent is the sum, `[N + M]`.
// Rows from two sources of any lengths, joined into one.
func joined<N, M>(head: &Tensor<f32, [N, 2]>, tail: &Tensor<f32, [M, 2]>) -> Tensor<f32, [N + M, 2]> {
Tensor::concat([head, tail], axis: 0)
}
func main() -> i32 {
val a: Tensor<f32, [2, 3]> = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
val b: Tensor<f32, [1, 3]> = [[7.0, 8.0, 9.0]]
// Parts may be borrowed or owned, and an operator result is a part like any other.
val rows = Tensor::concat([&a, &b], axis: 0)
val wide = Tensor::concat([&a, &a * 10.0], axis: -1)
println("rows: {rows[2, 0]} {rows.sum()}, wide: {wide[1, 5]}")
// Stacking at 0 makes a batch of two; at the end, pairs element by element.
val batch = Tensor::stack([&a, &a + 1.0], axis: 0)
val pairs = Tensor::stack([&a, &a + 1.0], axis: 2)
println("batch: {batch[1, 0, 0]}, pairs: {pairs[0, 2, 0]} {pairs[0, 2, 1]}")
// A borrowed receiver is read and stays usable; either half may be empty.
val (first, rest) = (&rows).split_at(axis: 0, at: 1)
val (left, right) = (&wide).split_at(axis: 1, at: 3)
println("first: {first.sum()}, rest: {rest.sum()}, right: {right[0, 0]}, same: {(&left == &a).all()}")
// Names carry through: the joined axis keeps the name the parts share.
val x: Tensor<f32, [batch: 2, feature: 2]> = [[1.0, 0.0], [0.0, 1.0]]
val y: Tensor<f32, [batch: 1, feature: 2]> = [[2.0, 2.0]]
val xy = Tensor::concat([&x, &y], axis: batch)
println("named: {xy.sum(axis: batch)[0]}")
// Generic extents: [2 + 1, 2] here.
val p: Tensor<f32, [2, 2]> = [[1.0, 1.0], [1.0, 1.0]]
val q: Tensor<f32, [1, 2]> = [[3.0, 3.0]]
val g = joined(&p, &q)
println("generic: {g.sum()}")
// A dynamic axis splits as well; the position is checked when the program runs.
val d = Tensor::<f32, [?B]>::zeros(dims: [5])
val (two, three) = (d + 1.0).split_at(axis: 0, at: 2)
println("dynamic: {two.sum()} {three.sum()}")
(rows.sum() + g.sum()) as i32
}
neuroc run tensor_join.nr
rows: 7.0 45.0, wide: 60.0
batch: 2.0, pairs: 3.0 4.0
first: 6.0, rest: 39.0, right: 10.0, same: true
named: 3.0
generic: 10.0
dynamic: 2.0 3.0