Skip to content

Commit

Permalink
Merge pull request #44 from BruceDai/add_more_reduction
Browse files Browse the repository at this point in the history
Implement more reduction
  • Loading branch information
huningxin authored Apr 10, 2023
2 parents e5917a0 + e9f927d commit 1ff3bbb
Show file tree
Hide file tree
Showing 2 changed files with 784 additions and 1 deletion.
61 changes: 60 additions & 1 deletion src/reduce.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
'use strict';

import {pow} from './binary.js';
import {squeeze} from './squeeze.js';
import {sizeOfShape, Tensor} from './lib/tensor.js';
import {abs, exp, log} from './unary.js';
import {sizeOfShape, Scalar, Tensor} from './lib/tensor.js';
import {validateReduceParams} from './lib/validate-input.js';

/**
Expand Down Expand Up @@ -120,3 +122,60 @@ export function reduceSum(input, options = {}) {
return reduce(input,
(previousValue, currentValue) => previousValue + currentValue, options);
}

/**
* Compute the sum of the square of all the input values along the axes.
* @param {Tensor} input
* @param {MLReduceOptions} options
* @return {Tensor}
*/
export function reduceSumSquare(input, options = {}) {
return reduceSum(pow(input, new Scalar(2)), options);
}

/**
* Compute the L1 norm of all the input values along the axes.
* @param {Tensor} input
* @param {MLReduceOptions} options
* @return {Tensor}
*/
export function reduceL1(input, options = {}) {
return reduceSum(abs(input), options);
}

/**
* Compute the L2 norm of all the input values along the axes.
* @param {Tensor} input
* @param {MLReduceOptions} options
* @return {Tensor}
*/
export function reduceL2(input, options = {}) {
const intermediateResult = reduceSumSquare(input, options);
if (intermediateResult.rank === 0) {
return new Tensor(
[],
[Math.pow(intermediateResult.getValueByIndex(0), 0.5)]);
} else {
return pow(intermediateResult, new Scalar(0.5));
}
}

/**
* Compute the log value of the sum of all the input values along the axes.
* @param {Tensor} input
* @param {MLReduceOptions} options
* @return {Tensor}
*/
export function reduceLogSum(input, options = {}) {
return log(reduceSum(input, options));
}

/**
* Compute the log value of the sum of the exponent of all the input values along the axes.
* @param {Tensor} input
* @param {MLReduceOptions} options
* @return {Tensor}
*/
export function reduceLogSumExp(input, options = {}) {
return log(reduceSum(exp(input), options));
}
Loading

0 comments on commit 1ff3bbb

Please sign in to comment.