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
26 changes: 18 additions & 8 deletions lib/util/matrix.js
Original file line number Diff line number Diff line change
Expand Up @@ -652,18 +652,28 @@ export default class Matrix {
* Returns a matrix that sampled along the axis.
* @param {number} n Sampled size
* @param {number} [axis] Axis to be sampled
* @param {number} [duplicate] Allow duplicate index or not
* @returns {[Matrix, number[]]} Sampled matrix and its original indexes
*/
sample(n, axis = 0) {
sample(n, axis = 0, duplicate = false) {
const k = this.sizes[axis]
const idx = []
for (let i = 0; i < n; i++) {
idx.push(Math.floor(Math.random() * (k - i)))
}
for (let i = n - 1; i >= 0; i--) {
for (let j = n - 1; j > i; j--) {
if (idx[i] <= idx[j]) {
idx[j]++
if (duplicate) {
for (let i = 0; i < n; i++) {
idx.push(Math.floor(Math.random() * k))
}
} else {
if (n > k) {
throw new MatrixException('Invalid sampled size.')
}
for (let i = 0; i < n; i++) {
idx.push(Math.floor(Math.random() * (k - i)))
}
for (let i = n - 1; i >= 0; i--) {
for (let j = n - 1; j > i; j--) {
if (idx[i] <= idx[j]) {
idx[j]++
}
}
}
}
Expand Down
51 changes: 51 additions & 0 deletions tests/lib/util/matrix.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -989,6 +989,29 @@ describe('Matrix', () => {
expect(expidx).toEqual(idx)
})

test.each([undefined, 0])('row(%p) duplicate index', axis => {
const n = 6
const org = Matrix.randn(3, 5)
const [mat, idx] = org.sample(n, axis, true)
expect(idx).toHaveLength(n)

const expidx = []
for (let k = 0; k < n; k++) {
for (let i = 0; i < org.rows; i++) {
let flg = true
for (let j = 0; j < org.cols; j++) {
flg &= mat.at(k, j) === org.at(i, j)
}
if (flg) {
expidx.push(i)
break
}
}
}
expect(expidx).toHaveLength(n)
expect(expidx).toEqual(idx)
})

test('col index', () => {
const n = 3
const org = Matrix.randn(10, 5)
Expand All @@ -1012,6 +1035,34 @@ describe('Matrix', () => {
expect(expidx).toEqual(idx)
})

test('col duplicate index', () => {
const n = 6
const org = Matrix.randn(3, 5)
const [mat, idx] = org.sample(n, 1, true)
expect(idx).toHaveLength(n)

const expidx = []
for (let k = 0; k < n; k++) {
for (let j = 0; j < org.cols; j++) {
let flg = true
for (let i = 0; i < org.rows; i++) {
flg &= mat.at(i, k) === org.at(i, j)
}
if (flg) {
expidx.push(j)
break
}
}
}
expect(expidx).toHaveLength(n)
expect(expidx).toEqual(idx)
})

test('fail invalid sampled size %p', () => {
const mat = Matrix.randn(5, 10)
expect(() => mat.sample(6, 0)).toThrow('Invalid sampled size.')
})

test.each([-1, 2])('fail invalid axis %p', axis => {
const mat = Matrix.randn(5, 10)
expect(() => mat.sample(4, axis)).toThrow('Invalid axis.')
Expand Down