• Stars
    star
    358
  • Rank 118,855 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 10 years ago
  • Updated 23 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Matrix manipulation and computation library

ml-matrix

Matrix manipulation and computation library.

Zakodium logo

Maintained by Zakodium

NPM version build status DOI npm download

Installation

$ npm install ml-matrix

Usage

As an ES module

import { Matrix } from 'ml-matrix';

const matrix = Matrix.ones(5, 5);

As a CommonJS module

const { Matrix } = require('ml-matrix');

const matrix = Matrix.ones(5, 5);

API Documentation

Examples

Standard operations

const { Matrix } = require('ml-matrix');

var A = new Matrix([
  [1, 1],
  [2, 2],
]);

var B = new Matrix([
  [3, 3],
  [1, 1],
]);

var C = new Matrix([
  [3, 3],
  [1, 1],
]);

Operations

const addition       = Matrix.add(A, B);   // addition       = Matrix [[4, 4], [3, 3], rows: 2, columns: 2]
const subtraction    = Matrix.sub(A, B);   // subtraction    = Matrix [[-2, -2], [1, 1], rows: 2, columns: 2]
const multiplication = A.mmul(B);          // multiplication = Matrix [[4, 4], [8, 8], rows: 2, columns: 2]
const mulByNumber    = Matrix.mul(A, 10);  // mulByNumber    = Matrix [[10, 10], [20, 20], rows: 2, columns: 2]
const divByNumber    = Matrix.div(A, 10);  // divByNumber    = Matrix [[0.1, 0.1], [0.2, 0.2], rows: 2, columns: 2]
const modulo         = Matrix.mod(B, 2);   // modulo         = Matrix [[1, 1], [1, 1], rows: 2, columns: 2]
const maxMatrix      = Matrix.max(A, B);   // max            = Matrix [[3, 3], [2, 2], rows: 2, columns: 2]
const minMatrix      = Matrix.min(A, B);   // max            = Matrix [[1, 1], [1, 1], rows: 2, columns: 2]

Inplace Operations

C.add(A);   // => C = C + A
C.sub(A);   // => C = C - A
C.mul(10);  // => C = 10 * C
C.div(10);  // => C = C / 10
C.mod(2);   // => C = C % 2

Math Operations

// Standard Math operations: (abs, cos, round, etc.)
var A = new Matrix([
  [ 1,  1],
  [-1, -1],
]);

var exponential = Matrix.exp(A);  // exponential = Matrix [[Math.exp(1), Math.exp(1)], [Math.exp(-1), Math.exp(-1)], rows: 2, columns: 2].
var cosinus     = Matrix.cos(A);  // cosinus     = Matrix [[Math.cos(1), Math.cos(1)], [Math.cos(-1), Math.cos(-1)], rows: 2, columns: 2].
var absolute    = Matrix.abs(A);  // absolute    = Matrix [[1, 1], [1, 1], rows: 2, columns: 2].
// Note: you can do it inplace too as A.abs()

Available Methods:

abs, acos, acosh, asin, asinh, atan, atanh, cbrt, ceil, clz32, cos, cosh, exp, expm1, floor, fround, log, log1p, log10, log2, round, sign, sin, sinh, sqrt, tan, tanh, trunc

Manipulation of the matrix

// remember: A = Matrix [[1, 1], [-1, -1], rows: 2, columns: 2]

var numberRows     = A.rows;             // A has 2 rows
var numberCols     = A.columns;          // A has 2 columns
var firstValue     = A.get(0, 0);        // get(rows, columns)
var numberElements = A.size;             // 2 * 2 = 4 elements
var isRow          = A.isRowVector();    // false because A has more than 1 row
var isColumn       = A.isColumnVector(); // false because A has more than 1 column
var isSquare       = A.isSquare();       // true, because A is 2 * 2 matrix
var isSym          = A.isSymmetric();    // false, because A is not symmetric
A.set(1, 0, 10);                         // A = Matrix [[1, 1], [10, -1], rows: 2, columns: 2]. We have changed the second row and the first column
var diag           = A.diag();           // diag = [1, -1] (values in the diagonal)
var m              = A.mean();           // m = 2.75
var product        = A.prod();           // product = -10 (product of all values of the matrix)
var norm           = A.norm();           // norm = 10.14889156509222 (Frobenius norm of the matrix)
var transpose      = A.transpose();      // transpose = Matrix [[1, 10], [1, -1], rows: 2, columns: 2]

Instantiation of matrix

var z = Matrix.zeros(3, 2); // z = Matrix [[0, 0], [0, 0], [0, 0], rows: 3, columns: 2]
var z = Matrix.ones(2, 3);  // z = Matrix [[1, 1, 1], [1, 1, 1], rows: 2, columns: 3]
var z = Matrix.eye(3, 4);   // z = Matrix [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], rows: 3, columns: 4]. there are 1 only in the diagonal

Maths

const {
  Matrix,
  inverse,
  solve,
  linearDependencies,
  QrDecomposition,
  LuDecomposition,
  CholeskyDecomposition,
  EigenvalueDecomposition,
} = require('ml-matrix');

Inverse and Pseudo-inverse

var A = new Matrix([
  [2, 3, 5],
  [4, 1, 6],
  [1, 3, 0],
]);

var inverseA = inverse(A);
var B = A.mmul(inverseA); // B = A * inverse(A), so B ~= Identity


// if A is singular, you can use SVD :
var A = new Matrix([
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
]); 
// A is singular, so the standard computation of inverse won't work (you can test if you don't trust me^^)

var inverseA = inverse(A, (useSVD = true)); // inverseA is only an approximation of the inverse, by using the Singular Values Decomposition
var B = A.mmul(inverseA); // B = A * inverse(A), but inverse(A) is only an approximation, so B doesn't really be identity.
// if you want the pseudo-inverse of a matrix :
var A = new Matrix([
  [1, 2],
  [3, 4],
  [5, 6],
]);

var pseudoInverseA = A.pseudoInverse();
var B = A.mmul(pseudoInverseA).mmul(A); // with pseudo inverse, A*pseudo-inverse(A)*A ~= A. It's the case here

Least square

Least square is the following problem: We search for x, such that A.x = B (A, x and B are matrix or vectors). Below, how to solve least square with our function

// If A is non singular :
var A = new Matrix([
  [3,    1],
  [4.25, 1],
  [5.5,  1],
  [8,    1],
]);

var B = Matrix.columnVector([4.5, 4.25, 5.5, 5.5]);
var x = solve(A, B);
var error = Matrix.sub(B, A.mmul(x)); // The error enables to evaluate the solution x found.
// If A is non singular :
var A = new Matrix([
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
]);

var B = Matrix.columnVector([8, 20, 32]);
var x = solve(A, B, (useSVD = true)); // there are many solutions. x can be [1, 2, 1].transpose(), or [1.33, 1.33, 1.33].transpose(), etc.
var error = Matrix.sub(B, A.mmul(x)); // The error enables to evaluate the solution x found.

Decompositions

QR Decomposition
var A = new Matrix([
  [2, 3, 5],
  [4, 1, 6],
  [1, 3, 0],
]);

var QR = new QrDecomposition(A);
var Q = QR.orthogonalMatrix;
var R = QR.upperTriangularMatrix;
// So you have the QR decomposition. If you multiply Q by R, you'll see that A = Q.R, with Q orthogonal and R upper triangular
LU Decomposition
var A = new Matrix([
  [2, 3, 5],
  [4, 1, 6],
  [1, 3, 0],
]);

var LU = new LuDecomposition(A);
var L = LU.lowerTriangularMatrix;
var U = LU.upperTriangularMatrix;
var P = LU.pivotPermutationVector;
// So you have the LU decomposition. P includes the permutation of the matrix. Here P = [1, 2, 0], i.e the first row of LU is the second row of A, the second row of LU is the third row of A and the third row of LU is the first row of A.
Cholesky Decomposition
var A = new Matrix([
  [2, 3, 5],
  [4, 1, 6],
  [1, 3, 0],
]);

var cholesky = new CholeskyDecomposition(A);
var L = cholesky.lowerTriangularMatrix;
Eigenvalues & eigenvectors
var A = new Matrix([
  [2, 3, 5],
  [4, 1, 6],
  [1, 3, 0],
]);

var e = new EigenvalueDecomposition(A);
var real = e.realEigenvalues;
var imaginary = e.imaginaryEigenvalues;
var vectors = e.eigenvectorMatrix;

Linear dependencies

var A = new Matrix([
  [2, 0, 0, 1],
  [0, 1, 6, 0],
  [0, 3, 0, 1],
  [0, 0, 1, 0],
  [0, 1, 2, 0],
]);

var dependencies = linearDependencies(A);
// dependencies is a matrix with the dependencies of the rows. When we look row by row, we see that the first row is [0, 0, 0, 0, 0], so it means that the first row is independent, and the second row is [ 0, 0, 0, 4, 1 ], i.e the second row = 4 times the 4th row + the 5th row.

License

MIT

More Repositories

1

ml

Machine learning tools in JavaScript
JavaScript
2,562
star
2

knn

A k-nearest neighboor classifier algorithm.
JavaScript
136
star
3

pca

Principal component analysis
TypeScript
96
star
4

kmeans

K-Means clustering
TypeScript
87
star
5

libsvm

LIBSVM for the browser and nodejs 🔥
JavaScript
82
star
6

levenberg-marquardt

Curve fitting method in JavaScript
JavaScript
70
star
7

distance

Distance functions to compare vectors
TypeScript
67
star
8

random-forest

Random forest for classification and regression.
JavaScript
61
star
9

hclust

Hierarchical clustering in JavaScript
JavaScript
53
star
10

naive-bayes

Naive bayes classifier.
JavaScript
48
star
11

regression

Regression algorithms
JavaScript
43
star
12

xgboost

A port of XGBoost to javascript with emscripten
C
41
star
13

svm

Support Vector Machine in Javascript
JavaScript
37
star
14

savitzky-golay

Savitzky–Golay filter
TypeScript
34
star
15

regression-multivariate-linear

Multivariate linear regression
JavaScript
33
star
16

feedforward-neural-networks

A implementation of feedforward neural networks based on wildml implementation
JavaScript
29
star
17

regression-simple-linear

Simple Linear Regression
TypeScript
28
star
18

decision-tree-cart

Decision trees using CART implementation
JavaScript
24
star
19

som

self-organizing map (SOM) / Kohonen network
JavaScript
23
star
20

logistic-regression

JavaScript
18
star
21

array

Functional utilities to transform and compute stats on arrays
JavaScript
16
star
22

regression-polynomial

Polynomial Regression
TypeScript
15
star
23

curve-fitting

Levenberg Marquardt curve-fitting: minimize sum of weighted squared residuals
JavaScript
14
star
24

confusion-matrix

Confusion matrix for supervised classification
TypeScript
12
star
25

pls

PLS regression algorithm
JavaScript
10
star
26

global-spectral-deconvolution

Global Spectra Deconvolution + Peak optimizer
TypeScript
9
star
27

savitzky-golay-generalized

General Least-Squares Smoothing and Differentiation by the Convolution (Savitzky-Golay) Method Peter A. Gorry
TypeScript
9
star
28

conrec

JavaScript implementation of the CONREC contouring algorithm
TypeScript
8
star
29

tree-similarity

Tree similarity in Javascript
TypeScript
8
star
30

convolution

Convolution using the FFT or direct algorithm.
JavaScript
8
star
31

fft

JavaScript
7
star
32

cross-validation

Utility library to make cross validation with supervised classifiers
JavaScript
7
star
33

spectra-processing

Various methods to help spectra processing
TypeScript
7
star
34

tree-set

A JavaScript emulator of the TreeSet Java class
JavaScript
6
star
35

bit-array

Bit-array operations in JavaScript
JavaScript
6
star
36

fcnnls

Fast Combinatorial Non-negative Least Squares
TypeScript
6
star
37

distance-euclidean

Compute the euclidean distance between two vectors
TypeScript
5
star
38

matrix-convolution

Matrix convolution.
JavaScript
5
star
39

anova

Analysis of variance
TypeScript
5
star
40

tanimoto

Tanimoto similarity and distance
JavaScript
4
star
41

combinations

Generate all possible unordered samples of size m, without replacement, from a set of n objects
JavaScript
4
star
42

array-xy

Functional utilities for sets of points
JavaScript
4
star
43

dataset-iris

Iris flower data set
TypeScript
4
star
44

dbscan

TypeScript
4
star
45

distance-matrix

Compute a distance-matrix based on a custom distance function
JavaScript
4
star
46

sparse-matrix

Sparse matrix library
JavaScript
4
star
47

floyd-warshall

Algorithm for finding shortest paths in a weighted graph with positive or negative edge weights (but with no negative cycles)
TypeScript
4
star
48

spectra-fitting

TypeScript
4
star
49

regression-robust-polynomial

Robust polynomial regression using LMedS
TypeScript
4
star
50

generator-mljs-packages

DEPRECATED
JavaScript
3
star
51

regression-exponential

Exponential Regression
JavaScript
3
star
52

xsadd

JavaScript implementation of the XORSHIFT-ADD (XSadd) pseudo random number generator
TypeScript
3
star
53

disjoint-set

Efficient disjoint-set data structure implementation
JavaScript
3
star
54

stat

Functions for computing stats on arrays and matrices
JavaScript
3
star
55

nmf

Non-negative Matrix Factorization (NMF)
JavaScript
3
star
56

performance

JavaScript
3
star
57

array-utils

Some array utilities in JavaScript
JavaScript
2
star
58

expectation-maximization

JavaScript
2
star
59

ml-pipe

TypeScript
2
star
60

airpls

Baseline correction using adaptive iteratively reweighted penalized least squares
JavaScript
2
star
61

regression-theil-sen

Method for robust fitting a line to a set of points
JavaScript
2
star
62

isolation-forest

JavaScript
2
star
63

binary-search

DEPRECATED
JavaScript
2
star
64

dataset

dataset for multivariate analysis
JavaScript
2
star
65

generate-dataset

Generate synthetic datasets for testing
JavaScript
2
star
66

statistics

JavaScript
2
star
67

signal-processing

TypeScript
2
star
68

pad-array

Array padding
JavaScript
2
star
69

pcr

TypeScript
2
star
70

random

Randomness utilities
TypeScript
2
star
71

matrix-peaks-finder

JavaScript
1
star
72

kernel

A factory for kernel functions
JavaScript
1
star
73

calculus

JavaScript
1
star
74

simulated-annealing

JavaScript
1
star
75

hash-table

Open addressing hash table with double hashing
JavaScript
1
star
76

dataset-metadata

a class to manipulate metadata for statistical analysis
JavaScript
1
star
77

datamining

Old repository to be split
JavaScript
1
star
78

peak-shape-generator

Generate various peak shapes.
TypeScript
1
star
79

regression-base

Base class for regression packages
TypeScript
1
star
80

preprocess

Preprocess functions to improve the representation and quality of data
JavaScript
1
star
81

regression-polynomial-2d

TypeScript
1
star
82

baseline-correction-regression

Iterative regression-based baseline correction.
JavaScript
1
star