Matrix Manipulation
Reshaping, transposing, permuting, concatenating, sorting, and other shape manipulation operations on INDArrays
Overview
Reshape
Basic reshape
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.api.ndarray.INDArray;
// 12-element source
INDArray src = Nd4j.arange(12);
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
INDArray mat = src.reshape(3, 4); // 3 rows x 4 cols
/*
[[ 0, 1.0000, 2.0000, 3.0000],
[ 4.0000, 5.0000, 6.0000, 7.0000],
[ 8.0000, 9.0000, 10.0000, 11.0000]]
*/
INDArray cube = src.reshape(2, 3, 2); // rank-3
/*
[[[ 0, 1.0000],
[ 2.0000, 3.0000],
[ 4.0000, 5.0000]],
[[ 6.0000, 7.0000],
[ 8.0000, 9.0000],
[ 10.0000, 11.0000]]]
*/Specifying memory order
reshape returns a view (shared data!)
Using -1 as a wildcard
Transpose
Out-of-place transpose (returns a view)
In-place transpose
Non-square matrices
Permute
Ravel and Flatten
ravel() — view when possible
Nd4j.toFlattened() — always a copy
Concatenation
Nd4j.concat — along any dimension
Nd4j.vstack — vertical stack (along rows)
Nd4j.hstack — horizontal stack (along columns)
Stack and Unstack
Nd4j.stack
Unstacking
Squeeze and Unsqueeze
Squeeze — remove size-1 dimensions
Unsqueeze — add a size-1 dimension
Sort
Sort along a dimension
sortRows and sortColumns
Repeat
Pad
Swap Axes
Views vs. Copies Reference
Operation
Returns
Practical Example: Preparing a Batch
API Reference Links
Last updated
Was this helpful?