(input, dim = null, keepdim = false)
| 1492 | * @returns {Tensor} A new tensor with means taken along the specified dimension. |
| 1493 | */ |
| 1494 | export function mean(input, dim = null, keepdim = false) { |
| 1495 | const inputDims = input.dims; |
| 1496 | const inputData = /** @type {Float32Array} */ (input.data); |
| 1497 | |
| 1498 | if (dim === null) { |
| 1499 | // None to reduce over all dimensions. |
| 1500 | const val = inputData.reduce((a, b) => a + b, 0); |
| 1501 | return new Tensor( |
| 1502 | input.type, |
| 1503 | [val / inputData.length], |
| 1504 | [ |
| 1505 | /* scalar */ |
| 1506 | ], |
| 1507 | ); |
| 1508 | } |
| 1509 | dim = safeIndex(dim, inputDims.length); |
| 1510 | |
| 1511 | // Compute sum |
| 1512 | const [type, result, resultDims] = reduce_helper((a, b) => a + b, input, dim, keepdim); |
| 1513 | |
| 1514 | // Divide by number of elements in the dimension |
| 1515 | if (inputDims[dim] !== 1) { |
| 1516 | for (let i = 0; i < result.length; ++i) { |
| 1517 | result[i] /= inputDims[dim]; |
| 1518 | } |
| 1519 | } |
| 1520 | |
| 1521 | return new Tensor(type, result, resultDims); |
| 1522 | } |
| 1523 | |
| 1524 | function dimsToStride(dims) { |
| 1525 | const stride = new Array(dims.length); |
no test coverage detected