Python Forum
How to quantize a 4 dimensional array? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to quantize a 4 dimensional array? (/thread-37018.html)



How to quantize a 4 dimensional array? - PythonNPC - Apr-23-2022

Hello,

I am new to NumPy.

Lets say I have an array:
nparray = np.array(output2)
print(output2.shape)
Output:
(1, 26, 26, 128)
All the values are floating point numbers. Most of them are 0.xxxxxxx, few are between 1.xxxxxxx to 4.xxxxxxx and extreme rare ones are above 5.xxxxxxx. They can be negative or positive.


I want to quantize these values into 8bit integers from the range -127 to 128. So that the largest value in the array becomes a 128 and the smallest value becomes a -127. I know there might be resolution loss but I am okay with it.

How can I achieve this using NumPy (or some other technique)?


RE: How to quantize a 4 dimensional array? - deanhystad - Apr-23-2022

numpy.interp() can be used to re-interpolate an array of values from one range to another.
Output:
import numpy as np floats = np.random.rand(10) print(floats) range_adjusted = np.interp(floats, (min(floats), max(floats)), (-128, 127)) ints = range_adjusted.astype("int8") print(ints)
Output:
[0.23561182 0.47971123 0.04360216 0.56386097 0.78886284 0.9104152 0.32166445 0.52518248 0.54179553 0.72678282] [ -71 0 -128 25 91 127 -46 13 18 72]
The array has to be a single dimension, but you can reshape down to one, do the value adjustments, then reshape back to 4 dimensions.


RE: How to quantize a 4 dimensional array? - Gribouillis - Apr-23-2022

This function seems to work
>>> def func(a):
...     l, u = np.amin(a), np.amax(a)
...     return np.rint((a - l) * (255 / (u - l))) - 127
... 
>>> import numpy as np
>>> t = np.random.rand(5, 7)
>>> t
array([[0.48858387, 0.51885553, 0.50699018, 0.14738217, 0.105979  ,
        0.53540183, 0.86726475],
       [0.80267188, 0.57738387, 0.32951204, 0.71753945, 0.35037134,
        0.93836202, 0.18163814],
       [0.20919502, 0.27296382, 0.20278684, 0.82154427, 0.15883035,
        0.27340079, 0.82762161],
       [0.23281187, 0.54044188, 0.28653632, 0.79343013, 0.20178373,
        0.61876179, 0.47841846],
       [0.71916377, 0.81516669, 0.17768047, 0.11852501, 0.86190322,
        0.1823391 , 0.508792  ]])
>>> func(t)
array([[ -10.,   -1.,   -4., -114., -127.,    5.,  106.],
       [  86.,   17.,  -59.,   60.,  -52.,  128., -104.],
       [ -95.,  -76.,  -97.,   92., -111.,  -76.,   94.],
       [ -88.,    6.,  -72.,   84.,  -98.,   30.,  -13.],
       [  61.,   90., -105., -123.,  105., -104.,   -4.]])