Bookmark this: tool.io/matrix/nonnegative-matrix-factorization/source-code
Nonnegative Matrix Factorization Demonstrator Source Code
Browse the implementation files for Nonnegative Matrix Factorization Demonstrator.tool.ts typescript
import { parseFiniteNumber } from '../../parse/number/tool';
import { parseInteger } from '../../parse/integer/tool';
import { createSeededRandom } from '../../random/seeded-number/tool';
const transpose = (matrix: number[][]): number[][] =>
matrix[0].map((_, column) =>
matrix.map((row) => row[column])
);
const multiply = (
left: number[][],
right: number[][]
): number[][] =>
left.map((row) =>
right[0].map((_, column) =>
row.reduce(
(sum, value, index) =>
sum + value * right[index][column],
0
)
)
);
const update = (
matrix: number[][],
numerator: number[][],
denominator: number[][]
): number[][] =>
matrix.map((row, i) =>
row.map(
(value, j) =>
(value * numerator[i][j]) /
Math.max(1e-12, denominator[i][j])
)
);
export const demonstrateNmf = (
matrixInput: unknown,
rankInput: unknown,
iterationsInput: unknown,
seedInput: unknown
): string => {
const rank = parseInteger(rankInput);
const iterations = parseInteger(iterationsInput);
if (
rank === null ||
rank < 1 ||
iterations === null ||
iterations < 1 ||
iterations > 10_000 ||
typeof matrixInput !== 'string' ||
typeof seedInput !== 'string' ||
!seedInput.trim()
)
return '';
let source: unknown;
try {
source = JSON.parse(matrixInput);
} catch {
return '';
}
if (
!Array.isArray(source) ||
!source.length ||
source.some(
(row) =>
!Array.isArray(row) ||
!row.length ||
row.some(
(value) =>
typeof value !== 'number' ||
!Number.isFinite(value) ||
value < 0
)
) ||
new Set(source.map((row) => row.length)).size !== 1 ||
rank > Math.min(source.length, source[0].length) ||
source.length * source[0].length * rank * iterations >
10_000_000
)
return '';
const values = source as number[][];
const random = createSeededRandom(seedInput);
let w = Array.from({ length: values.length }, () =>
Array.from({ length: rank }, () => 0.1 + random())
);
let h = Array.from({ length: rank }, () =>
Array.from(
{ length: values[0].length },
() => 0.1 + random()
)
);
for (
let iteration = 0;
iteration < iterations;
iteration += 1
) {
h = update(
h,
multiply(transpose(w), values),
multiply(multiply(transpose(w), w), h)
);
w = update(
w,
multiply(values, transpose(h)),
multiply(w, multiply(h, transpose(h)))
);
}
const reconstruction = multiply(w, h);
const loss = Math.sqrt(
values.reduce(
(sum, row, i) =>
sum +
row.reduce(
(inner, value, j) =>
inner + (value - reconstruction[i][j]) ** 2,
0
),
0
)
);
if (
!Number.isFinite(loss) ||
w.some((row) =>
row.some((value) => !Number.isFinite(value))
) ||
h.some((row) =>
row.some((value) => !Number.isFinite(value))
) ||
reconstruction.some((row) =>
row.some((value) => !Number.isFinite(value))
)
)
return '';
const roundMatrix = (matrix: number[][]) =>
matrix.map((row) =>
row.map((value) => Number(value.toPrecision(8)))
);
return JSON.stringify(
{
h: roundMatrix(h),
loss: Number(loss.toPrecision(8)),
reconstruction: roundMatrix(reconstruction),
w: roundMatrix(w)
},
null,
2
);
};
export const Tool: TypeTool = {
name: 'Nonnegative Matrix Factorization Demonstrator',
slug: 'matrix/nonnegative-matrix-factorization',
intro:
'Factor a small nonnegative matrix with seeded multiplicative-update NMF.',
tool: demonstrateNmf,
i: [
{
example: '[[1,0,1],[0,1,1],[1,1,2]]',
label: 'Nonnegative Matrix',
placeholder: 'Matrix as JSON',
render: 'textarea',
type: 'text'
},
{
example: '2',
label: 'Rank',
placeholder: 'Factorization rank',
type: 'number'
},
{
example: '100',
label: 'Iterations',
placeholder: 'Update iterations',
type: 'number'
},
{
example: 'tool.io',
label: 'Seed',
placeholder: 'Reproducible seed',
type: 'text'
}
],
o: [
{
example: '{ "w": [], "h": [], "loss": 0.1 }',
label: 'NMF Factors',
placeholder: 'Factors will appear here...',
render: 'textarea',
type: 'text'
}
],
cite: [
{
title: 'Non-negative matrix factorization - Wikipedia',
url: 'https://en.wikipedia.org/wiki/Non-negative_matrix_factorization'
}
]
};
export default Tool;
Description
Browse the implementation files for Nonnegative Matrix Factorization Demonstrator.