Skip to content

Commit

Permalink
feat: add variance and standardDeviation methods
Browse files Browse the repository at this point in the history
  • Loading branch information
targos committed Apr 18, 2019
1 parent 6b57aae commit f42f1b6
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
2 changes: 2 additions & 0 deletions matrix.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,8 @@ declare module 'ml-matrix' {
pseudoInverse(threshold?: number): Matrix;
clone(): Matrix;
entropy(eps?: number): number;
variance(unbiased?: boolean, means?: number[]): number[];
standardDeviation(unbiased?: boolean, means?: number[]): number[];

// From here we document methods dynamically generated from operators

Expand Down
54 changes: 53 additions & 1 deletion src/abstractMatrix.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,14 @@ import {
checkRange,
checkIndices
} from './util';
import { sumByRow, sumByColumn, sumAll, productByRow, productByColumn, productAll } from './stat';
import {
sumByRow,
sumByColumn,
sumAll,
productByRow,
productByColumn,
productAll
} from './stat';
import MatrixTransposeView from './views/transpose';
import MatrixRowView from './views/row';
import MatrixSubView from './views/sub';
Expand Down Expand Up @@ -1778,6 +1785,51 @@ export default function AbstractMatrix(superCtor) {
}
return 0 - sum;
}

variance(unbiased = true, means = this.mean('column')) {
if (typeof unbiased !== 'boolean') {
throw new TypeError('unbiased must be a boolean');
}
if (!Array.isArray(means)) {
throw new TypeError('means must be an array');
}

const rows = this.rows;
const cols = this.columns;
const variance = [];

for (var j = 0; j < cols; j++) {
var sum1 = 0;
var sum2 = 0;
var x = 0;
for (var i = 0; i < rows; i++) {
x = this.get(i, j) - means[j];
sum1 += x;
sum2 += x * x;
}
if (unbiased) {
variance.push((sum2 - (sum1 * sum1) / rows) / (rows - 1));
} else {
variance.push((sum2 - (sum1 * sum1) / rows) / rows);
}
}
return variance;
}

standardDeviation(unbiased = true, means = this.mean('column')) {
if (typeof unbiased !== 'boolean') {
throw new TypeError('unbiased must be a boolean');
}
if (!Array.isArray(means)) {
throw new TypeError('means must be an array');
}

const variance = this.variance(means, unbiased);
for (var i = 0; i < variance.length; i++) {
variance[i] = Math.sqrt(variance[i]);
}
return variance;
}
}

Matrix.prototype.klass = 'Matrix';
Expand Down

0 comments on commit f42f1b6

Please sign in to comment.