How to normalize negative number in numpy array

Question:

I have video features as numpy files (.npy) with the shape of (15, 2048) with positive and negative value. I want to normalize it so that all the values are positive only. The numpy array is something like this:

array([[-1.4004713 ,  0.6517762 , -0.11610898, ...,  0.3231497 ,
         0.10557604, -1.0216804 ],
       [-0.34153703,  1.2883852 ,  0.16293666, ..., -0.53560203,
        -0.067341  ,  0.00724552],
       [ 0.877613  ,  0.11527498, -0.45193946, ..., -0.16771363,
         0.38475066, -0.284884  ],
       ...,
       [-0.5748145 ,  0.08665206,  0.27134556, ..., -0.03541826,
         0.05377219, -0.62528425],
       [-0.02782645, -0.04130568, -0.0581201 , ...,  1.2714614 ,
         0.7328908 ,  0.2180524 ],
       [-0.28007308,  1.2357589 , -0.04791486, ...,  0.14003311,
         1.0041502 , -0.47158736]], dtype=float32)

I tried this code but it didn’t work:

 Result = np.where(a >= 0, a/np.max(a), -a/np.min(a)) 
Asked By: adeljalalyousif

||

Answers:

Assuming you want to normalize to the global min and max, and there are no NaNs, the normalized array is given by:

(arr - arr.min()) / (arr.max() - arr.min())

If you have NaNs, rephrase this with np.nanmin() and np.nanmax().

Answered By: kwinkunks
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.