As I've described in a StackOverflow question, I'm trying to fit a NumPy array into a certain range.
Here is the solution I currently use:
import numpy as np
def scale_array(dat, out_range=(-1, 1)):
domain = [np.min(dat, axis=0), np.max(dat, axis=0)]
def interp(x):
return out_range[0] * (1.0 - x) + out_range[1] * x
def uninterp(x):
b = 0
if (domain[1] - domain[0]) != 0:
b = domain[1] - domain[0]
else:
b = 1.0 / domain[1]
return (x - domain[0]) / b
return interp(uninterp(dat))
print(scale_array(np.array([-2, 0, 2], dtype=np.float)))
# Gives: [-1., 0., 1.]
print(scale_array(np.array([-3, -2, -1], dtype=np.float)))
# Gives: [-1., 0., 1.]
Is there a way to make this code cleaner? Is there a built-in function in NumPy or scikit-learn? This feels like a really common data pre-processing step and it feels weird that I keep re-implementing it.