Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy array to bounded by 0 and 1?

Basically I have an array that may vary between any two numbers, and I want to preserve the distribution while constraining it to the [0,1] space. The function to do this is very very simple. I usually write it as:

def to01(array):
    array -= array.min()
    array /= array.max()
    return array

Of course it can and should be more complex to account for tons of situations, such as all the values being the same (divide by zero) and float vs. integer division (use np.subtract and np.divide instead of operators). But this is the most basic.

The problem is that I do this very frequently across stuff in my project, and it seems like a fairly standard mathematical operation. Is there a built in function that does this in NumPy?

like image 892
user3557216 Avatar asked Sep 11 '14 20:09

user3557216


People also ask

How do I cap a NumPy array?

To limit the values of the NumPy array ndarray to given range, use np. clip() or clip() method of ndarray . By specifying the minimum and maximum values in the argument, the out-of-range values are replaced with those values. This is useful when you want to limit the values to a range such as 0.0 ~ 1.0 or 0 ~ 255 .

How do I normalize a NumPy array to 1?

In order to normalize a vector in NumPy, we can use the np. linalg. norm() function, which returns the vector's norm value. We can then use the norm value to divide each value in the array to get the normalized array.

What does [: :] mean on NumPy arrays?

The [:, :] stands for everything from the beginning to the end just like for lists. The difference is that the first : stands for first and the second : for the second dimension. a = numpy. zeros((3, 3)) In [132]: a Out[132]: array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]])


1 Answers

Don't know if there's a builtin for that (probably not, it's not really a difficult thing to do as is). You can use vectorize to apply a function to all the elements of the array:

def to01(array):
    a = array.min()
    # ignore the Runtime Warning
    with numpy.errstate(divide='ignore'):
        b = 1. /(array.max() - array.min())
    if not(numpy.isfinite(b)):
        b = 0
    return numpy.vectorize(lambda x: b * (x - a))(array)
like image 163
greschd Avatar answered Oct 13 '22 11:10

greschd