I have a large number of numpy vectors, each of shape (3,) with 8 bit integer values:
vec = np.random.randint(2**8, size=3)
I'd like to quantize those vectors to a smaller space by some known reduction factor. I know I can hammer this out in a series of operations by defining another vector with values that define the amount of information loss, dividing vec
by that vector, then cooercing the resulting values back to integers:
>>> vec = np.random.randint(2**8, size=3)
>>> denominator = np.full(3, 8)
>>> divided = vec / denominator
>>> ints = divided.astype(int)
>>> ints *= denominator
>>>
>>> vec
array([205, 182, 99])
>>> ints
array([200, 176, 96])
Is there a faster way to quantize these numpy vectors though? I'd be very grateful for any ideas others can share on this question.
Assuming that your reduction factor is a power of two, the operation you are showing amounts to clearing the last few bits. This can be done in one step using the bitwise and operator &
. You can specify the bitmask directly using Python binary literals 0b11111000
or do 256 - denominator
. So thanks to numpy broadcasting all you need to do is
vec & (256 - denominator)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With