Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions lib/util/matrix.js
Original file line number Diff line number Diff line change
Expand Up @@ -1802,21 +1802,30 @@ export default class Matrix {
* @returns {Matrix<number> | number} Variance values
*/
variance(axis = -1, ddof = 0) {
const m = this.mean(axis)
if (axis < 0) {
return this._value.reduce((acc, v) => acc + (v - m) ** 2, 0) / (this.length - ddof)
let v = 0
let v2 = 0
const den = this.length - ddof
for (let i = 0; i < this.length; i++) {
v += this._value[i]
v2 += this._value[i] ** 2
}
return v2 / den - (v / den) ** 2
}
let v_step = axis === 0 ? 1 : this.cols
let s_step = axis === 0 ? this.cols : 1
const new_size = [].concat(this._size)
new_size[axis] = 1
const den = this._size[axis] - ddof
const mat = Matrix.zeros(...new_size)
for (let n = 0, nv = 0; n < mat.length; n++, nv += v_step) {
let v = 0
let v2 = 0
for (let i = 0; i < this._size[axis]; i++) {
v += (this._value[i * s_step + nv] - m._value[n]) ** 2
v += this._value[i * s_step + nv]
v2 += this._value[i * s_step + nv] ** 2
}
mat._value[n] = v / (this._size[axis] - ddof)
mat._value[n] = v2 / den - (v / den) ** 2
}
return mat
}
Expand Down
6 changes: 3 additions & 3 deletions tests/lib/util/matrix.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2663,7 +2663,7 @@ describe('Matrix', () => {
[4, 5, 6],
]
const org = new Matrix(2, 3, data)
expect(org.variance()).toBe(17.5 / 6)
expect(org.variance()).toBeCloseTo(17.5 / 6)
})

test('axis 0', () => {
Expand All @@ -2685,7 +2685,7 @@ describe('Matrix', () => {
const org = new Matrix(2, 3, data)
const prod = org.variance(1)
expect(prod.sizes).toEqual([2, 1])
expect(prod.value).toEqual([8 / 3, 8 / 3])
expect(prod.value).toEqual([expect.closeTo(8 / 3), expect.closeTo(8 / 3)])
})
})

Expand Down Expand Up @@ -2718,7 +2718,7 @@ describe('Matrix', () => {
const org = new Matrix(2, 3, data)
const prod = org.std(1)
expect(prod.sizes).toEqual([2, 1])
expect(prod.value).toEqual([Math.sqrt(8 / 3), Math.sqrt(8 / 3)])
expect(prod.value).toEqual([expect.closeTo(Math.sqrt(8 / 3)), expect.closeTo(Math.sqrt(8 / 3))])
})
})

Expand Down