A reduction operation returns a tensor with fewer dimensions than the original by applying a reduction operator to slices of values. You specify the dimensions to reduce using an array of integers (the "reduction dimensions").
Key Rules for Reduction Dimensions:
- The parameter can have at most as many elements as the rank of the input tensor.
- Each element must be less than the tensor rank.
- Each dimension should occur at most once in the reduction dimensions.
- Listing dimensions in increasing order may improve execution speed.
Special Case: Reduction along all dimensions
If you pass no parameter to a reduction operation, the original tensor is reduced along all its dimensions, resulting in a zero-dimension tensor (a scalar).
Predefined Reduction Operators:
sum(): Returns the sum of reduced values.mean(): Returns the mean of reduced values.maximum(): Returns the largest of the reduced values.minimum(): Returns the smallest of the reduced values.prod(): Returns the product of the reduced values.all(): Casts tensor to bool and checks if all elements are true (note: does not short-circuit).any(): Casts tensor to bool and checks if any element is true (note: does not short-circuit).
Custom Reductions
You can use reduce(const Dimensions& new_dims, const Reducer& reducer) to apply a user-defined reduction operator by implementing a reductor template.
// Example: Reduction along one dimension
Eigen::Tensor<int, 2> a(2, 3);
a.setValues({{1, 2, 3}, {6, 5, 4}});
// Reduce along the second dimension (index 1)
Eigen::array<int, 1> dims({1});
Eigen::Tensor<int, 1> b = a.maximum(dims);
// b will be: [3, 6]
// Example: Reduction along all dimensions (returns scalar)
Eigen::Tensor<float, 3> a(2, 3, 4);
Eigen::Tensor<float, 0> b = a.sum();