Search code examples
pythonscikit-learnnormalization

scaling data to specific range in python


I would like to scale an array of size [192,4000] to a specific range. I would like each row (1:192) to be rescaled to a specific range e.g. (-840,840). I run a very simple code:

import numpy as np
from sklearn import preprocessing as sp
sample_mat = np.random.randint(-840,840, size=(192, 4000))
scaler = sp.MinMaxScaler(feature_range=(-840,840))
scaler = scaler.fit(sample_mat)
scaled_mat= scaler.transform(sample_mat)

This messes up my matrix range, even when max and min of my original matrix is exactly the same. I can't figure out what is wrong, any idea?


Solution

  • You can do this manually. It is a linear transformation of the minmax normalized data.

    interval_min = -840
    interval_max = 840
    scaled_mat = (sample_mat - np.min(sample_mat) / (np.max(sample_mat) - np.min(sample_mat)) * (interval_max - interval_min) + interval_min