[PYTHON] Standardize the vector to any range

There are many opportunities to standardize an appropriate vector $ v $ into the range $ [0, 1] $ and $ [-1, 1] $. Now create $ v $ as a vector with random numbers like this:

random_vector.py



import random
random.seed(1)
v = [random.random() for _ in range(10)]

In the python code above, $ v $ is given, for example:

figure_1.png

To standardize this vector to the range $ [0,1], [-1,1] $, respectively:

-Standardized to $ [0,1] $


\frac{v - min(v)}{max(v) - min(v)}

-Standardized to $ [-1,1] $


\frac{2v - (max(v) + min(v))}{max(v)-min(v)}

This will linearly standardize $ v $.

figure_2.png

However, there are times when you want to ** standardize ** a vector to ** arbitrary range ** [newmin, newmax].

In such a case, first calculate two constants $ a and b $.


a = (newmax - newmin)/(max(v) - min(v)) \\
b = newmax - a*max(v)

At this time, the same is true for $ b = newmin --a * min (v) $.

Finally, create a linear function ** with ** $ a $ tilting and $ b $ as the intercept, and substitute the original vector $ v $ to get a new linearly standardized vector.


normalized\ vector = a*v + b

This is the general form for linearly standardizing vectors.

Here is the code that standardizes the vector $ v $ in the range [newmin, newmax] in Python and Matlab.


Python

normalize.py



def normalize(v,newmin,newmax):
    a = (newmax - newmin)/(max(v) - min(v))
    b = newmax - a*max(v)
        
    return [a*i + b for i in v]


Matlab

normalize.m



function [normalized_vector] = normalize(v, newmin, newmax)

a = (newmax - newmin)/(max(v) - min(v));
b = newmax - max(v)*a;

normalized_vector = a*v + b;


Recommended Posts

Standardize the vector to any range
Set the range of active strips to the preview range
[Introduction to Python] How to iterate with the range function?
The road to Pythonista
The road to Djangoist
Keras I want to get the output of any layer !!
How to use the generator
The road to download Matplotlib
How to use the decorator
How to increase the axis
How to start the program