Home > other >  How to group/round/quantize similar values in a numpy array
How to group/round/quantize similar values in a numpy array

Time:06-28

Is there a numpy method that let's me recover a numpy array's quantized structure if I don't know in advance what the quantized values/levels are, but do know for example that they are spaced > 1.0 apart?

For example:

import numpy as np
x = np.array([0.5, 0.5, 1.75, 1.75, 1.75,6.45,6.45,0.5, 11.1, 0.5, 6.45])
x_noise = x   np.random.randn(len(x))/100

Is there a way to solve for x given just x_noise?

CodePudding user response:

If you don't know anything else about the original quantized values, I think the best you can do is to average over the noise:

sort_idx = np.argsort(x_noise)
# group values that are less than 1.0 apart
splits = np.where(np.diff(x_noise[sort_idx]) > 1.0)[0]   1
groups = np.split(x_noise[sort_idx], splits)
# reconstruct x with the average values
x_approx = np.empty_like(x_noise)
for idx, group in zip(np.split(sort_idx, splits), groups):
    x_approx[idx] = np.mean(group)
  • Related