+1 vote
in Programming Languages by (40.5k points)
I want to transform the values in a matrix by scaling each of them to a given range. Is there any Pythonic way to do it?

1 Answer

+2 votes
by (71.8k points)
selected by
 
Best answer

There are several ways to scale the values in a matrix to a given range. One common Pythonic approach is to use the MinMaxScaler class of the scikit-learn library.

Here's an example to scale value within range [0, 5]:

>>> from sklearn.preprocessing import MinMaxScaler

>>> import numpy as np

>>> x=np.asarray([[-1, 3], [-5, 6], [7, 10], [1, -18]])

>>> x

array([[ -1,   3],

       [ -5,   6],

       [  7,  10],

       [  1, -18]])

>>> scaler = MinMaxScaler(feature_range=(0, 5))

>>> x1=scaler.fit_transform(x)

>>> x1

array([[1.66666667, 3.75      ],

       [0.        , 4.28571429],

       [5.        , 5.        ],

       [2.5       , 0.        ]])


...