Minmaxscaler Python Code

python minmaxscaler

MinMaxScaler in scikit-learn: Python code and examples

MinMaxScaler in Python: scale features without leaking test data

MinMaxScaler applies a separate linear transformation to each feature using its fitted minimum and maximum. With the default range, a nonconstant training feature is mapped to [0, 1].

Fit on training data, then transform: validation or test values outside the training range can map below 0 or above 1. Setting clip=True clips those values, but can hide how far they fall outside the training range.

Min-max scaling does not remove outliers or make a distribution normal. Use our feature-scaling guide to compare alternatives. During cross-validation, put the scaler inside the model pipeline so each fold learns its own scaling.

Turn the concepts into a working ML project. Read the free Starter Kit excerpt on test sets to preview the €19 handbook. No email required.

For a nonconstant feature, the default transform is (x − training_min) / (training_max − training_min). Scikit-learn handles constant features without dividing by zero. See the MinMaxScaler documentation.

You can learn all about Feature Scaling in Machine Learning with the article linked here, but in short it consists on making the features of our data all have similar value ranges, which is of great importance for any kind of algorithm that uses a distance metric like K-Nearest Neighbours (KNN), K-means clustering, and many others.

In this short snippet we will show you the code needed to do this, explaining every step and parameter involved in detail.

First we need to start with the import, like shown in the following block of code

from sklearn.preprocessing import MinMaxScaler

From the preprocessing tools in Sklearn we will import MinMaxScaler

Now, we need some data. For our example we will use a data set that has two features: one is weight in Kg and one is height in meters. The following figure shows that these features variate over very different ranges:

Minmaxscaler python
Weight and Height features. As we can see the weight feature has a much broader range of values than the height feature. This leads us to wanting to scale our data.

The data points in our vector look like the following, where the first column depicts the height and the second one the weight

# Illustrative training rows: [height in metres, weight in kg]
data_vector = [
    [1.76, 58], [1.96, 101], [1.31, 66], [1.64, 98],
    [1.57, 91], [1.29, 63], [2.09, 51], [1.74, 67]
]

To scale the data first we need to create a MinMaxScaler Python object, like shown in the 1st line of code of the following block, and after that we have to train it using our data, which we do in the second line.

scaler = MinMaxScaler()
scaler.fit(data_vector)

By doing this we will get the MinmaxScaler Python object to learn the characteristics of our data and its ranges, so that it can later transform all of it to the required scale. In other words, the fit( ) method computes the minimum and maximum of our data to be used for later scaling.

Note that in the previous block we are giving the MinmaxScaler Python object a vector as an input, but we could have given it a pandas Datafrrame too, like shown in the following block:

import pandas as pd

df_train = pd.DataFrame({
    "A": [14.00, 90.20, 90.95, 96.27, 91.21],
    "B": [103.02, 107.26, 110.35, 114.23, 114.68]
})
# Separate scaler for this separate example.
df_scaler = MinMaxScaler()
df_scaler.fit(df_train[["A", "B"]])

Once the MinMaxScaler object is trained, we can use it to scale our data using the transform( ) method:

scaled_data = scaler.transform(data_vector)

Which will give us an scaled output array if we used an array, like in the following block showing scaled_data, which is the scaled version of our data_vector:

# First two rows, rounded to four decimal places:
# [[0.5875, 0.1400],
#  [0.8375, 1.0000]]
print(scaled_data[:2].round(4))

This could have also been done for Dataframe columns like so:

df_scaled = df_train.copy()
df_scaled[["A", "B"]] = df_scaler.transform(df_train[["A", "B"]])

Awesome, lets see how our data looks like now!

Minmaxscaler python example

We have learnt how to use the MinMaxScaler Python object to effectively scale our data.

For new rows, call transform with the already-fitted scaler and the same feature order. Do not fit a new scaler on test data. For example, a height above the training maximum of 2.09 m maps above 1 with the default clip=False.

Also, for other awesome books and courses about Python and Machine Learning, check out our reviews:

Book reviews:

Courses

Thanks a lot for reading, have a great day, and keep learning!

Illustration of the 90-day machine learning roadmap PDF

Stay on track. Get the Roadmap.

Download the 90-Day Roadmap PDF + get weekly tips and resources to help you succeed

Subscribe to our awesome newsletter to get the best content on your journey to learn Machine Learning, including some exclusive free goodies!

HOW IS MACHINE LEARNING