reduce()
combines rearrangement and reduction using
reader-friendly notation.
Arguments
- x
tensor: array, matrix, or list of arrays of the same shape and type
- expr
string: reduction pattern
- func
string or function: one of available reductions ('min', 'max', 'sum', 'mean', 'prod', 'any', 'all'), or an R 2 argument function which takes in two arguments, with the first being the tensor, and the second being an integer array indicating the dimensions to reduce over.
- ...
either corresponding axes lengths or a single list of them.
- .row_major
logical: whether to use row-major order for the output tensor. If
TRUE
, the operation is performed in row-major order, but the output will be in whatever order the parent framework uses (e.g. column-major forbase::array()
).
Examples
if (requireNamespace("abind", quietly = TRUE)) {
set.seed(42)
# Suppose x is a 3D array: 100 x 32 x 64
x <- array(rnorm(100 * 32 * 64), dim = c(100, 32, 64))
# perform max-reduction on the first axis
# Axis t does not appear on RHS - thus we reduced over t
y <- reduce(x, 't b c -> b c', 'max')
# same as previous, but using verbose names for axes
y <- reduce(x, 'time batch channel -> batch channel', 'max')
# let's pretend now that x is a batch of images
# with 4 dims: batch=10height = 20width = 30channel = 40
x <- array(rnorm(10 * 20 * 30 * 40), dim = c(10, 20, 30, 40))
# 2d max-pooling with kernel size = 2 * 2 for image processing
y1 <- reduce(x, 'b c (h1 h2) (w1 w2) -> b c h1 w1', 'max', h2 = 2, w2 = 2)
as_image_tensor(y1)
# same as previous, using anonymous axes,
# note: only reduced axes can be anonymous
y1 <- reduce(x, 'b c (h1 2) (w1 2) -> b c h1 w1', 'max')
as_image_tensor(y1)
# adaptive 2d max-pooling to 3 * 4 grid,
# each element is max of 10x10 tile in the original tensor.
dim(reduce(x, 'b c (h1 h2) (w1 w2) -> b c h1 w1', 'max', h1 = 3, w1 = 4))
# (10, 20, 3, 4)
# Global average pooling
dim(reduce(x, 'b c h w -> b c', 'mean'))
# (10, 20)
}
#> [1] 10 20