-1

I have created quantized values as: {0.0, 0.5, 1.0} and would like to do quantization for a vector based on the set. For instance, given vector [0.1, 0.1, 0.9, 0.8, 0.6, 0.6] would be transferred into [0.0, 0.0, 1.0, 1.0, 0.5, 0.5].

Please guide me fastest way using python/numpy/pytorch. Thank you very much!

kiranr
  • 2,087
  • 14
  • 32
hhle88
  • 53
  • 1
  • 4

1 Answers1

2

use map() and lambda()

you can get the round off nearest to 0.5 with round(x * 2) / 2

a = [0.1, 0.1, 0.9, 0.8, 0.6, 0.6]

list(map(lambda x: round(x * 2) / 2, a))

output :

[0.0, 0.0, 1.0, 1.0, 0.5, 0.5]
kiranr
  • 2,087
  • 14
  • 32
  • Thanks a lot. It works for my case. In fact, I would like to do for a dynamic range of the base, I mean not only for step of 0.5. For example, with step is 0.1, we have a base as {0.0, 0.1, 0.2,..., 0.9, 1.0} (even higher density with smaller step). I believe I can solve the question based on your answer. – hhle88 Mar 02 '21 at 01:42
  • in that case just use [round()](https://docs.python.org/3/library/functions.html#round) `round(n, 1)` where n is the float you want to pass. – kiranr Mar 02 '21 at 02:05
  • oh, that's right! Many thanks again for your help. – hhle88 Mar 02 '21 at 02:18