The Wayback Machine - https://web.archive.org/web/20240712160400/https://www.geeksforgeeks.org/data-pre-processing-wit-sklearn-using-standard-and-minmax-scaler/
Open In App

Data Pre-Processing with Sklearn using Standard and Minmax scaler

Last Updated : 03 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Data Scaling is a data preprocessing step for numerical features. Many machine learning algorithms like Gradient descent methods, KNN algorithm, linear and logistic regression, etc. require data scaling to produce good results. Various scalers are defined for this purpose. This article concentrates on Standard Scaler and Min-Max scaler. The task here is to discuss what they mean and how they are implemented using in-built functions that come with this package.

Apart from supporting library functions other functions that will be used to achieve the functionality are:

  • The fit(data) method is used to compute the mean and std dev for a given feature so that it can be used further for scaling.
  • The transform(data) method is used to perform scaling using mean and std dev calculated using the .fit() method.
  • The fit_transform() method does both fit and transform.

Standard Scaler

Standard Scaler helps to get standardized distribution, with a zero mean and standard deviation of one (unit variance). It standardizes features by subtracting the mean value from the feature and then dividing the result by feature standard deviation. 

The standard scaling is calculated as: 

z = (x - u) / s

Where,

  • z is scaled data.
  • x is to be scaled data.
  • u is the mean of the training samples
  • s is the standard deviation of the training samples.

Sklearn preprocessing supports StandardScaler() method to achieve this directly in merely 2-3 steps.

Syntax: class sklearn.preprocessing.StandardScaler(*, copy=True, with_mean=True, with_std=True)

Parameters:

  • copy: If False, inplace scaling is done. If True , copy is created instead of inplace scaling.
  • with_mean: If True, data is centered before scaling.
  • with_std: If True, data is scaled to unit variance.

Approach:

  • Import module
  • Create data
  • Compute required values
  • Print processed data

Example:

Python3




# import module
from sklearn.preprocessing import StandardScaler
 
# create data
data = [[11, 2], [3, 7], [0, 10], [11, 8]]
 
# compute required values
scaler = StandardScaler()
model = scaler.fit(data)
scaled_data = model.transform(data)
 
# print scaled data
print(scaled_data)


Output:

[[ 0.97596444 -1.61155897]

 [-0.66776515  0.08481889]

 [-1.28416374  1.10264561]

 [ 0.97596444  0.42409446]]

MinMax Scaler

There is another way of data scaling, where the minimum of feature is made equal to zero and the maximum of feature equal to one. MinMax Scaler shrinks the data within the given range, usually of 0 to 1. It transforms data by scaling features to a given range. It scales the values to a specific value range without changing the shape of the original distribution.

The MinMax scaling is done using:

x_std = (x – x.min(axis=0)) / (x.max(axis=0) – x.min(axis=0))

x_scaled = x_std * (max – min) + min

Where,

  • min, max = feature_range
  • x.min(axis=0) : Minimum feature value
  • x.max(axis=0):Maximum feature value

Sklearn preprocessing defines MinMaxScaler() method to achieve this.

Syntax: class sklearn.preprocessing.MinMaxScaler(feature_range=0, 1, *, copy=True, clip=False)

Parameters:

  • feature_range: Desired range of scaled data. The default range for the feature returned by MinMaxScaler is  0 to 1. The range is provided in tuple form as (min,max).
  • copy: If False, inplace scaling is done. If True , copy is created instead of inplace scaling.
  • clip: If True, scaled data is clipped to provided feature range.

Approach:

  • Import module
  • Create data
  • Scale data
  • print scaled data

Example:

Python3




# import module
from sklearn.preprocessing import MinMaxScaler
 
# create data
data = [[11, 2], [3, 7], [0, 10], [11, 8]]
 
# scale features
scaler = MinMaxScaler()
model=scaler.fit(data)
scaled_data=model.transform(data)
 
# print scaled features
print(scaled_data)


 

 

Output:

 

[[1.         0.        ]

[0.27272727 0.625     ]

[0.         1.        ]

[1.         0.75      ]]

 



Similar Reads

Python Sklearn – sklearn.datasets.load_breast_cancer() Function
In this article, we are going to see how to convert sklearn dataset to a pandas dataframe in Python. Sklearn is a python library that is used widely for data science and machine learning operations. Sklearn library provides a vast list of tools and functions to train machine learning models. The library is available via pip install. pip install sci
2 min read
CNN - Image data pre-processing with generators
The article aims to learn how to pre-processing the input image data to convert it into meaningful floating-point tensors for feeding into Convolutional Neural Networks. Just for the knowledge tensors are used to store data, they can be assumed as multidimensional arrays. A tensor representing a 64 X 64 image having 3 channels will have its dimensi
3 min read
Pre-processing and Modelling using Caret Package in R
Pre-processing and modeling are important phases in the field of data science and machine learning that affect how well predictive models work. Classification and Regression Training, or the "caret" package in R, is a strong and adaptable tool intended to make training and assessing machine learning models easier. This post will cover the fundament
5 min read
Do Clustering Algorithms Need Feature Scaling in the Pre-Processing Stage?
Answer: Yes, clustering algorithms typically require feature scaling to ensure equal distance consideration across all features.Without scaling, features with larger scales dominate the distance calculations, leading to biased clusters. Here's a comparison table to illustrate the impact of feature scaling on different clustering algorithms: Cluster
1 min read
What is the difference between batch processing and real-time processing?
In this article, we will learn about two fundamental methods that govern the flow of information and understand how data gets processed in the digital world. We start with simple definitions of batch processing and real-time processing, and gradually cover the unique characteristics and differences. Table of Content Data processing in Data Engineer
4 min read
Passing categorical data to Sklearn Decision Tree
Theoretically, decision trees are capable of handling numerical as well as categorical data, but, while implementing, we need to prepare the data for classification. There are two methods to handle the categorical data before training: one-hot encoding and label encoding. In this article, we understand how each method helps in converting categorica
5 min read
Encoding Categorical Data in Sklearn
Categorical data is a common occurrence in many datasets, especially in fields like marketing, finance, and social sciences. Unlike numerical data, categorical data represents discrete values or categories, such as gender, country, or product type. Machine learning algorithms, however, require numerical input, making it essential to convert categor
6 min read
Difference between Data Cleaning and Data Processing
Data Processing: It is defined as Collection, manipulation, and processing of collected data for the required use. It is a task of converting data from a given form to a much more usable and desired form i.e. making it more meaningful and informative. Using Machine Learning algorithms, mathematical modelling and statistical knowledge, this entire p
2 min read
What is Big Data, and How Does it Differ from Traditional Data Processing?
Big Data, as the name suggests, is a collection of Huge data that requires a high velocity of processing through various means like social media, sensors, transactions etc. Traditional DA processing involves entities and statistics, a consistent and intentional input; in contrast, Big Data includes structured, semi-structured, and unstructured cont
9 min read
Processing of Raw Data to Tidy Data in R
The data that is download from web or other resources are often hard to analyze. It is often needed to do some processing or cleaning of the dataset in order to prepare it for further downstream analysis, predictive modeling and so on. This article discusses several methods in R to convert the raw dataset into a tidy data. Raw Data A Raw data is a
5 min read
Practice Tags :