Many machine learning algorithms make assumptions about your data.

It is often a very good idea to prepare your data in such way to best expose the structure of the problem to the machine learning algorithms that you intend to use.

In this post you will discover how to prepare your data for machine learning in Python using scikit-learn.

Let’s get started.

## Need For Data Preprocessing

You almost always need to preprocess your data. It is a required step.

A difficulty is that different algorithms make different assumptions about your data and may require different transforms. Further, when you follow all of the rules and prepare your data, sometimes algorithms can deliver better results without the preprocessing.

Generally, I would recommend creating many different views and transforms of your data, then exercise a handful of algorithms on each view of your dataset. This will help you to flush out which data transforms might be better at exposing the structure of your problem in general.

### Need help with Machine Learning in Python?

Take my free 2-week email course and discover data prep, algorithms and more (with sample code).

Click to sign-up now and also get a free PDF Ebook version of the course.

## Preprocessing Machine Learning Recipes

This section lists 4 different data preprocessing recipes for machine learning.

All of the recipes were designed to be complete and standalone.

You can copy and paste them directly into your project and start working.

The Pima Indian diabetes dataset is used in each recipe. This is a binary classification problem where all of the attributes are numeric and have different scales. It is a great example of dataset that can benefit from pre-processing.

You can learn more about this data set on the UCI Machine Learning Repository webpage.

Each recipe follows the same structure:

- Load the dataset from a URL.
- Split the dataset into the input and output variables for machine learning.
- Apply a preprocessing transform to the input variables.
- Summarize the data to show the change.

The transforms are calculated in such a way that they can be applied to your training data and any samples of data you may have in the future.

The scikit-learn documentation has some information on how to use various different preprocessing methods. You can review the preprocess API in scikit-learn here.

### 1. Rescale Data

When your data is comprised of attributes with varying scales, many machine learning algorithms can benefit from rescaling the attributes to all have the same scale.

Often this is referred to as normalization and attributes are often rescaled into the range between 0 and 1. This is useful for optimization algorithms in used in the core of machine learning algorithms like gradient descent. It is also useful for algorithms that weight inputs like regression and neural networks and algorithms that use distance measures like K-Nearest Neighbors.

You can rescale your data using scikit-learn using the MinMaxScaler class.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Rescale data (between 0 and 1) import pandas import scipy import numpy from sklearn.preprocessing import MinMaxScaler url = "https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data" names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] dataframe = pandas.read_csv(url, names=names) array = dataframe.values # separate array into input and output components X = array[:,0:8] Y = array[:,8] scaler = MinMaxScaler(feature_range=(0, 1)) rescaledX = scaler.fit_transform(X) # summarize transformed data numpy.set_printoptions(precision=3) print(rescaledX[0:5,:]) |

After rescaling you can see that all of the values are in the range between 0 and 1.

1 2 3 4 5 |
[[ 0.353 0.744 0.59 0.354 0. 0.501 0.234 0.483] [ 0.059 0.427 0.541 0.293 0. 0.396 0.117 0.167] [ 0.471 0.92 0.525 0. 0. 0.347 0.254 0.183] [ 0.059 0.447 0.541 0.232 0.111 0.419 0.038 0. ] [ 0. 0.688 0.328 0.354 0.199 0.642 0.944 0.2 ]] |

### 2. Standardize Data

Standardization is a useful technique to transform attributes with a Gaussian distribution and differing means and standard deviations to a standard Gaussian distribution with a mean of 0 and a standard deviation of 1.

It is most suitable for techniques that assume a Gaussian distribution in the input variables and work better with rescaled data, such as linear regression, logistic regression and linear discriminate analysis.

You can standardize data using scikit-learn with the StandardScaler class.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Standardize data (0 mean, 1 stdev) from sklearn.preprocessing import StandardScaler import pandas import numpy url = "https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data" names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] dataframe = pandas.read_csv(url, names=names) array = dataframe.values # separate array into input and output components X = array[:,0:8] Y = array[:,8] scaler = StandardScaler().fit(X) rescaledX = scaler.transform(X) # summarize transformed data numpy.set_printoptions(precision=3) print(rescaledX[0:5,:]) |

The values for each attribute now have a mean value of 0 and a standard deviation of 1.

1 2 3 4 5 |
[[ 0.64 0.848 0.15 0.907 -0.693 0.204 0.468 1.426] [-0.845 -1.123 -0.161 0.531 -0.693 -0.684 -0.365 -0.191] [ 1.234 1.944 -0.264 -1.288 -0.693 -1.103 0.604 -0.106] [-0.845 -0.998 -0.161 0.155 0.123 -0.494 -0.921 -1.042] [-1.142 0.504 -1.505 0.907 0.766 1.41 5.485 -0.02 ]] |

### 3. Normalize Data

Normalizing in scikit-learn refers to rescaling each observation (row) to have a length of 1 (called a unit norm in linear algebra).

This preprocessing can be useful for sparse datasets (lots of zeros) with attributes of varying scales when using algorithms that weight input values such as neural networks and algorithms that use distance measures such as K-Nearest Neighbors.

You can normalize data in Python with scikit-learn using the Normalizer class.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Normalize data (length of 1) from sklearn.preprocessing import Normalizer import pandas import numpy url = "https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data" names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] dataframe = pandas.read_csv(url, names=names) array = dataframe.values # separate array into input and output components X = array[:,0:8] Y = array[:,8] scaler = Normalizer().fit(X) normalizedX = scaler.transform(X) # summarize transformed data numpy.set_printoptions(precision=3) print(normalizedX[0:5,:]) |

The rows are normalized to length 1.

1 2 3 4 5 |
[[ 0.034 0.828 0.403 0.196 0. 0.188 0.004 0.28 ] [ 0.008 0.716 0.556 0.244 0. 0.224 0.003 0.261] [ 0.04 0.924 0.323 0. 0. 0.118 0.003 0.162] [ 0.007 0.588 0.436 0.152 0.622 0.186 0.001 0.139] [ 0. 0.596 0.174 0.152 0.731 0.188 0.01 0.144]] |

### 4. Binarize Data (Make Binary)

You can transform your data using a binary threshold. All values above the threshold are marked 1 and all equal to or below are marked as 0.

This is called binarizing your data or threshold your data. It can be useful when you have probabilities that you want to make crisp values. It is also useful when feature engineering and you want to add new features that indicate something meaningful.

You can create new binary attributes in Python using scikit-learn with the Binarizer class.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# binarization from sklearn.preprocessing import Binarizer import pandas import numpy names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] dataframe = pandas.read_csv(url, names=names) array = dataframe.values # separate array into input and output components X = array[:,0:8] Y = array[:,8] binarizer = Binarizer(threshold=0.0).fit(X) binaryX = binarizer.transform(X) # summarize transformed data numpy.set_printoptions(precision=3) print(binaryX[0:5,:]) |

You can see that all values equal or less than 0 are marked 0 and all of those above 0 are marked 1.

1 2 3 4 5 |
[[ 1. 1. 1. 1. 0. 1. 1. 1.] [ 1. 1. 1. 1. 0. 1. 1. 1.] [ 1. 1. 1. 0. 0. 1. 1. 1.] [ 1. 1. 1. 1. 1. 1. 1. 1.] [ 0. 1. 1. 1. 1. 1. 1. 1.]] |

## Summary

In this post you discovered how you can prepare your data for machine learning in Python using scikit-learn.

You now have recipes to:

- Rescale data.
- Standardize data.
- Normalize data.
- Binarize data.

Your action step for this post is to type or copy-and-paste each recipe and get familiar with data preprocesing in scikit-learn.

Do you have any questions about data preprocessing in Python or this post? Ask in the comments and I will do my best to answer.

Hey Jason,

On Normalizing, do you need to do this if you are planning on using euclidean, or cosine distance measures to find similar items in a dataframe?

e.g. you have a vector where each column has some attributes about the product, and you want to find other products that have similar attributes.

Keen to hear your thoughts

Thanks

SM

Excellent!

Thanks Ernest.

Hi Jason,

Thanks for the post and the website overall. It really explains a lot.

I have a question regarding preparing the data ,if I am to normalize my Input data, does the precision of the values have an effect ? Will it make the weight matrix more sparse while training with higher precision if the training data is not very high?

In that case should I be limiting the precision depending on the amount of training data?

I am interested in sequence classification for EEG, In my case I intend to try out RNN . I was planning on normalizing the data since I wish the scaling to be performed on each individual input sequence.

Hoping to hear from you,thanks !

Great question Akshay.

I don’t have a clear answer for you. It may. I have not seen it have an effect, but I would not rule it out.

If you’re worried, I would recommend testing with samples of your data at different precisions and different transforms and evaluate the effect.

I expect the configuration of your model will be a much larger leaver on performance.

Hi Jason,Thank you for the reply.

I intend to build an RNN from scratch for the application similar to sentiment analysis (Many to one). I am a bit confused about the final stage. while training, when I feed a single sequence(belong to one of the class) to the training set , do I apply softmax to the last output of the network alone and compute the loss and leave the rest unattended?

Where exactly is the many to “ONE” represented?

Sorry Akshay, I don’t have example of implementing an RNN from scratch.

My advice would be to peek into the source code for standard deep learning library like Keras.

Should one normalize the test and train datasets separately? or does he have to normalize the whole dataset, before splitting it?

Yes. Normalize the train dataset and use the min/max from train to normalize the test set.

In this case, min/max of test set might be smaller or bigger than min/max of the training set. If they are, would it cause a problem to the validation?

You should estimate them using domain knowledge if possible, otherwise, estimate from train and clip test data if they exceed the known bounds.

Hi Jason, I often read about people normalize on the input features, but not on output, why?

Should we normalize on the output features as well if the output have a wide range of scale too? from 1e-3 to 1e3

BTW, it is for a regression problem.

You can normalize the output variable in regression too, but you will need to reverse the scaling of predictions in order to make use of them or quote error scores in a meaningful way (e.g. meaningful to your problem).

The MSE loss is very high (1e8) when I didn’t applied normalization on the output variable, and small MSE loss (0.0xxx) when I applied normalization.

Is there something wrong in my implementation? Should I run large epochs(maybe 50000?) when the output variable isn’t normalized? (currently running 500 epochs with normalization).

Perhaps. Continue to try different things and see if you can learn more about your system/problem.

@Roy,

– if you don’t normalize and the features are not of similar scale, then the gradient descent would take a very long time to converge [1]

– if Root MSE is much much smaller than the mean/median value of the predicted vector, I think your model is good enough

[1] Stranford.edu: https://www.youtube.com/watch?v=yQci-wS0iMw&list=PLZ9qNFMHZ-A4rycgrgOYma6zxF4BZGGPW&index=21https://www.youtube.com/watch?v=yQci-wS0iMw&list=PLZ9qNFMHZ-A4rycgrgOYma6zxF4BZGGPW&index=21

Normalizing input variables is an intent to make the underlying relationship between input and output variables easier to model.

Your tutorials are awesome. 🙂

I have converted rescaledX to a dataframe and plotted histogram for rescaling, standardization and normalization. They all seem to be scaling down the magnitude of an attribute to a small range — 0 to 1 in case of rescaling and normalization.

– are they doing similar transformation i.e. scaling down attributes so they become comparable?

– do you only apply one method in any given situation?

– which would be appropriate in which situation?

Thanking in advance.

Good questions.

This post explains how they work and when to use them:

http://machinelearningmastery.com/how-to-scale-data-for-long-short-term-memory-networks-in-python/

Hi Jason, I really like your posts. I was looking for some explanation on using power transformations on data for scaling. Like using logarithms and exponents and stuff like that. I would really like to understand what it does to the data and how we as data scientist can be power users of such scaling techniques

The best advice is to try a suite of transforms and see what results in the more predictive model.

I have a few posts on power transforms like log and boxcox, try the search feature.

Hi Jason,thanks for your all posts , I have question related to Multilayer Perceptron classification algorithm

if we want to apply this algorithm on mixed data set (numeric and nominal).

EX (23,125,75,black,green) this data presents the age ,length,weight ,Hair color, Eye color Respectively.

For numeric attributes we will normalize the data to be in the same range.

what about nominal attributes?

Do we need to transform nominal attributes to binary attributes?

I would recommend either using an integer encoding or a one hot encoding.

It is common to use a one hot encoding.

I have many posts on the topic.

Hello Jason, great post

However,

I have a question (maybe is almost the same that Dimos).

What is the most often approach to preprocess (I mean use 1 of 4 explained)

How values you normalize?

all features (X)

fit_transform train features(X_train_std=model.fit_trainsform(X_train)) and from them transform X_test (X_test_std=model.transform(X_test))

and then:

If we have to predict new features that I get today(for example: 0,95,80,45,92,36.5,0.330,26,0 in diabetes model)

we have to preprocess that feature or is not necessary relevant and predict it without preprocess:

Thank you for help

Any process used to prepare data for training the model must be performed when making predictions on new data with the final model.

This means coefficients used in scaling (e.g. min/max) are really part of the model and must be chosen mindfully.

thak you for your answer

Hi Jason

I am applying normalization for network attacker data. i used min/max normalization. but in the real data there is some features have a large values. if i want to apply standard deviation normalization. should i apply only one normalization type? or can i apply min/max for all data and then apply standard deviation for all data. what is the sequence and is it wrong if i apply standard deviation normalization only on the large value features?

I would recommend trying both approaches and see what works best for your data and models.