Linear Algebra in JavaScript with Matrix Operations - Robin Wieruch

Linear Algebra in JavaScript with Matrix Operations - Robin Wieruch

When I recently started to dive into the topic of machine learning, I had to relearn all the things I have studied about linear algebra, stochastic and calculus at school and university. I took a little refresher on matrix operations (addition, subtraction, multiplication and division) in linear algebra and learned about the different types of matrices (inverse matrix, transpose matrix, identity matrix) again. The article is a refresher about those things and applies them in JavaScript. Furthermore, in the end of the article, there will be a little example to demonstrate why matrices are beneficial for computations in machine learning. In addition, you will find a couple of tips on how to express mathematical equations in JavaScript similar to Octave or Matlab.

A matrix is just an array in an array when programming with them. In JavaScript, they can be simply expressed as:

whereas m equals the row and n equals the column of a matrix[m][n]. A vector is a specific kind of a matrix whereas the matrix has only one column.

The most simple mathematical object in linear algebra is a scalar. It is just a single number.

Matrices and vectors can be expressed with arrays in programming. But what about matrices with more than two dimensions? They need more than two axes. In general, these arrays of numbers with a variable number of axes are called tensors.

You should be able to apply matrix operations all by yourself, but it can become ugly when using plain JavaScript with loops. Fortunately, there exists a library in JavaScript for mathematics called math.js . Defining a matrix becomes as simple as:

You can get its dimension by using the size() method and its value as array with the valueOf() method. Furthermore, you can apply matrix operations such as addition, subtraction, multiplication and division:

Note that for instance the product of a matrix in the case of math.js is not just a new matrix containing the product of the individual matrices. This would be called an element-wise product (or Hardamard product ). Instead it is a matrix product operation.

In addition, you can perform matrix scalar multiplication and division as well. It’s performed element-wise.

Since a vector is only a specific form of a matrix, you can perform matrix-vector multiplication too.

In case you want to have an element-wise multiplication or division in JavaScript, you can use math.dotMultiply(matrixI, vectorJ); or math.dotDivide(matrixY, matrixZ) . Otherwise, when using the default operators on matrices with math.js, you will apply the default matrix operations.

After all, dealing with matrices in math.js isn’t that difficult anymore. But you have to know the dimensions of each matrix in your operation, because not every matrix operates on another matrix. Another good thing to know are the associative and commutative matrix operations.

There are two important properties for matrix multiplication. First, matrix multiplication is not commutative: A x B != B x A.

Second, matrix multiplication is associative: A x (B x C) == (A x B) x C.

These matrix multiplication properties should be internalized before making any further more complex operations on matrices.

There are a couple of other matrix operations and matrix types in linear algebra. First, the Identity (I) Matrix with the dimension i * j is defined as i-dimensional matrix whereas i == j. The following matrix is an identity matrix.

In math.js you can use the eye(i) method to generate those with the dimension of i.

Identity matrices are used later on for more sophisticated matrix operations. Used with another matrix in a matrix operation, identity matrices are a special case because they are commutative: A x I == I x A.

Another type of matrix is the transposed matrix. It is a matrix where the dimensions are flipped. Basically the rows become columns and the columns become rows. In the following example, the vector becomes a so-called row vector.

Last but not least, matrices can have an inverse A’ but not all matrices (called singular or degenerate) have one. You can find the inverse of a matrix by using the identity matrix: A(A’) = (A’)A = I.

Math.js gives you the inverse operation for free. You can use the same matrix from the previous example and call the inv() method on it.

In the end, regardless of the programming language you are using, you will find one powerful math library such as math.js to apply all of these operations.

The previous learnings gave a basic understanding of linear algebra with matrices used in JavaScript. How does it help us in machine learning? You can take the example of linear regression . Matrix operations can be used to make linear regression simpler to execute and computational efficient. But also other machine learning algorithms in the future. For instance, when having three (trained) competing hypotheses functions for a linear regression, it becomes simple with matrices to calculate their results.

You can put these computations in matrices now, rather than executing every function on its own. A loop becomes one matrix operation. On a higher level you can say that a unvectorized implementation becomes a vectorized implementation . Thus it becomes computational efficient when performing machine learning algorithms and simpler as well. Furthermore, these matrix operations are used in a normal equation by default which is used as an alternative to gradient descent.

At some point, using math.js the proposed way doesn’t scale anymore. You will do more than one matrix operation in complex mathematical expressions. What about the following expressions?

Yes, it is taken from a multivariate linear regression with gradient descent . It can be easily expressed in mathematical programming languages such as Matlab or Octave. In math.js it wouldn’t scale when using the standard methods.

That’s a mess. However, fortunately you can do it concise by using the eval functionality that takes a mathematical expression and the scoped values to apply those in the expression.

Still not as concise as using Octave or Matlab, but you can evaluate complex mathematical expression now. It helps you in other scenarios too. For instance, it can be used to extract a subset of a Matrix by range indices:

It returns the first and second column (indices start with 1) with all their rows as two vectors in a new matrix. It goes even further by assigning columns in a matrix a new vector.

In conclusion, I hope the walkthrough about matrices applied in JavaScript was helpful to get started in the linear algebra in JavaScript or as foundation for machine learning in JavaScript. You can checkout the GitHub repository with executable matrix operations on the command line. If you like it, make sure to star it.

Recommended articles