简体   繁体   中英

Fast way to quantize numpy vectors

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM