+3 votes
in Programming Languages by (17.0k points)
I have a 2D matrix that has different numeric values. I want to normalize the values of matrix elements so that they are 0<= v<= 1. How can I do the normalization in Python?

1 Answer

0 votes
by (29.3k points)

To normalize the matrix elements, you can use the following formula:

{\displaystyle X'={\frac {X-X_{\min }}{X_{\max }-X_{\min }}}}

It will set the value of each element between 0 and 1.

Here is an example:

>>> import numpy as np
>>> X = np.array([[4, 1, 2, 2],[1, 3, 9, 3], [5, 7, 5, 1]])
>>> X
array([[4, 1, 2, 2],
       [1, 3, 9, 3],
       [5, 7, 5, 1]])
>>> np.divide(X-X.min(axis=0),(X.max(axis=0)-X.min(axis=0)))
array([[0.75      , 0.        , 0.        , 0.5       ],
       [0.        , 0.33333333, 1.        , 1.        ],
       [1.        , 1.        , 0.42857143, 0.        ]])

 You can also use sklearn's Normalizer() to normalize the matrix elements.

Here is an example:

>>> import numpy as np
>>> from sklearn.preprocessing import Normalizer
>>> X = np.array([[4, 1, 2, 2],[1, 3, 9, 3], [5, 7, 5, 1]])
>>> X
array([[4, 1, 2, 2],
       [1, 3, 9, 3],
       [5, 7, 5, 1]])
>>> transformer = Normalizer().fit(X)
>>> transformer.transform(X)

array([[0.8, 0.2, 0.4, 0.4],
       [0.1, 0.3, 0.9, 0.3],
       [0.5, 0.7, 0.5, 0.1]])

...