Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I standardize a matrix?

Basically, take a matrix and change it so that its mean is equal to 0 and variance is 1. I'm using numpy's arrays so if it can already do it it's better, but I can implement it myself as long as I can find an algorithm.

edit: nvm nimrodm has a better implementation

like image 242
pnodbnda Avatar asked Sep 07 '25 12:09

pnodbnda


1 Answers

The following subtracts the mean of A from each element (the new mean is 0), then normalizes the result by the standard deviation.

import numpy as np
A = (A - np.mean(A)) / np.std(A)

The above is for standardizing the entire matrix as a whole, If A has many dimensions and you want to standardize each column individually, specify the axis:

import numpy as np
A = (A - np.mean(A, axis=0)) / np.std(A, axis=0)

Always verify by hand what these one-liners are doing before integrating them into your code. A simple change in orientation or dimension can drastically change (silently) what operations numpy performs on them.

like image 127
nimrodm Avatar answered Sep 10 '25 13:09

nimrodm