How to min-max scale a 2d numpy array globally

Viewed 38

I have this mini example for my greater task at hand:

from sklearn.preprocessing import minmax_scale

arr = np.array([[1,2,3],[4,5,6],[11,12,13]])
print(arr)

scaled_array = minmax_scale(arr, axis=0)

print(scaled_array)

The output is:

[[ 1  2  3]
 [ 4  5  6]
 [11 12 13]]
[[0.  0.  0. ]
 [0.3 0.3 0.3]
 [1.  1.  1. ]]

Unfortunately I can only get it to scale to (0,1) column-wise or row-wise. I would like to have this array globally scaled.

So the output I would like to have would be:

[[0.   0.08 0.16]
 [0.25 0.33 0.41]
 [0.83 0.91 1]]

How do I do this other than checking globally for the minimum value and then checking for the maximum value and then manually calculating it for every entry in my two-dimensional array (which I don't want to do because it's not very efficient for my greater task at hand)?


Edit:

So I have written my own function to do this:

min_value = np.amin(arr)
max_value = np.amax(arr)
arr = arr.astype(np.float64)

for x in np.nditer(arr, order='C', op_flags=['readwrite']):
    scaled_value = (x-min_value)/(max_value-min_value)
    x[...]=scaled_value

This does produce the wanted outcome. I am still wondering if there is a similar method like minmax_scale from sklearn.preprocessing that might do what I would like to do. Does anyone have an idea?

1 Answers

You can apply .minmax_scale to a flattened array, and then reshape it back to the original shape:

minmax_scale(arr.flatten()).reshape(arr.shape)

Output:

array([[0.        , 0.08333333, 0.16666667],
       [0.25      , 0.33333333, 0.41666667],
       [0.83333333, 0.91666667, 1.        ]])
Related