tf.keras.ops.average  |  TensorFlow v2.16.1 (original) (raw)

Compute the weighted average along the specified axis.

View aliases

Main aliases

tf.keras.ops.numpy.average

tf.keras.ops.average(
    x, axis=None, weights=None
)
Args
x Input tensor.
axis Integer along which to average x. The default, axis=None, will average over all of the elements of the input tensor. If axis is negative it counts from the last to the first axis.
weights Tensor of wieghts associated with the values in x. Each value in x contributes to the average according to its associated weight. The weights array can either be 1-D (in which case its length must be the size of a along the given axis) or of the same shape as x. If weights=None (default), then all data in x are assumed to have a weight equal to one.The 1-D calculation is: avg = sum(a * weights) / sum(weights). The only constraint on weights is that sum(weights) must not be 0.
Returns
Return the average along the specified axis.

Examples:

data = keras.ops.arange(1, 5) data array([1, 2, 3, 4], dtype=int32) keras.ops.average(data) array(2.5, dtype=float32) keras.ops.average( keras.ops.arange(1, 11), weights=keras.ops.arange(10, 0, -1) ) array(4., dtype=float32)

data = keras.ops.arange(6).reshape((3, 2)) data array([[0, 1], [2, 3], [4, 5]], dtype=int32) keras.ops.average( data, axis=1, weights=keras.ops.array([1./4, 3./4]) ) array([0.75, 2.75, 4.75], dtype=float32) keras.ops.average( data, weights=keras.ops.array([1./4, 3./4]) ) Traceback (most recent call last): `` ValueError: Axis must be specified when shapes of a and weights differ.