Your data must be prepared before you can build models. The data preparation process can involve three steps: data selection, data preprocessing and data transformation.

In this post you will discover two simple data transformation methods you can apply to your data in Python using scikit-learn.

**Update**: See this post for a more up to date set of examples.

## Data Rescaling

Your preprocessed data may contain attributes with a mixtures of scales for various quantities such as dollars, kilograms and sales volume.

Many machine learning methods expect or are more effective if the data attributes have the same scale. Two popular data scaling methods are normalization and standardization.

### Need help with Machine Learning in Python?

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

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

## Data Normalization

Normalization refers to rescaling real valued numeric attributes into the range 0 and 1.

It is useful to scale the input attributes for a model that relies on the magnitude of values, such as distance measures used in k-nearest neighbors and in the preparation of coefficients in regression.

The example below demonstrate data normalization of the Iris flowers dataset.

1 2 3 4 5 6 7 8 9 10 11 |
# Normalize the data attributes for the Iris dataset. from sklearn.datasets import load_iris from sklearn import preprocessing # load the iris dataset iris = load_iris() print(iris.data.shape) # separate the data from the target attributes X = iris.data y = iris.target # normalize the data attributes normalized_X = preprocessing.normalize(X) |

For more information see the normalize function in the API documentation.

## Data Standardization

Standardization refers to shifting the distribution of each attribute to have a mean of zero and a standard deviation of one (unit variance).

It is useful to standardize attributes for a model that relies on the distribution of attributes such as Gaussian processes.

The example below demonstrate data standardization of the Iris flowers dataset.

1 2 3 4 5 6 7 8 9 10 11 |
# Standardize the data attributes for the Iris dataset. from sklearn.datasets import load_iris from sklearn import preprocessing # load the Iris dataset iris = load_iris() print(iris.data.shape) # separate the data and target attributes X = iris.data y = iris.target # standardize the data attributes standardized_X = preprocessing.scale(X) |

For more information see the scale function in the API documentation.

## Tip: Which Method To Use

It is hard to know whether rescaling your data will improve the performance of your algorithms before you apply them. If often can, but not always.

A good tip is to create rescaled copies of your dataset and race them against each other using your test harness and a handful of algorithms you want to spot check. This can quickly highlight the benefits (or lack there of) of rescaling your data with given models, and which rescaling method may be worthy of further investigation.

## Summary

Data rescaling is an important part of data preparation before applying machine learning algorithms.

In this post you discovered where data rescaling fits into the process of applied machine learning and two methods: Normalization and Standardization that you can use to rescale your data in Python using the scikit-learn library.

**Update**: See this post for a more up to date set of examples.

Hi thank you for this nice article ! I have a quick question (maybe long to explain but I think the answer is short 🙂 )

I am using data standardization for a k-NN algorithm. I will have new instances and I’ll have to determine their class, their data won’t be standardized.

Should I :

1) Standardize my training set with the scale function. Then manually calculate the means and the std of my training set to standardize my new vector.

2) Add the new data to the training set and then standardize the set with the mean function.

3) Neither

Thank you !

Great question Matt.

Generally, it is a good idea to calculate the rescale parameters using the training data and use those parameters to rescale the test dataset and all datasets that needs predictions going forward.

You can and should use the StandardScaler() object that has the means and standard deviations inside.

See this post for a more up to date example:

http://machinelearningmastery.com/prepare-data-machine-learning-python-scikit-learn/

I came across your website which is extremely helpful for studying machine learning. Thanks for the great effort.

Just a friendly reminder. The normalization function has an axis parameter with a default value equals to 1, so it will run on rows/data by default. For feature normalization, you need to set axis = 0.

Thanks Tzu-Yen!

Hey Tzu-Yen, you saved my day…. Thanks a lot

Hi Jason,

May i know how to bring the data back to original scale? I need my predictions in original scale. I normalised by data and tried .inverse_transform(data) to get back my original data. But it gave me an error – AttributeError: ‘Normalizer’ object has no attribute ‘inverse_transform’

Any kind of help would be appreciated.

I would recommend using the MinMaxScaler instead:

http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html

Hi Jason,

I have one question.

Suppose today my data range is 5000 to 10000 which will be scaled between 0 to 1

And tomorrow if new data entry comes with 10500. if I use same 5000 to 10000 range for fitting then it produce output X1 and and If i specify 5000 to 10500 range then it produce output X2 which is not equal to X1.

How to over come this? How to handle new data with old range?

Thanks & Regards

Sumit

You can estimate the expected range of data in the future and those min/max to scale.

Or, you can estimate a mean/stdev and standardize instead, if the data is Gaussian.

Hi Jason, when I use standardization as suggested in the post, I see mean and standard deviation very close to zero and one, respectively…but not exactly. Wonder if such close-enough values are acceptable in the community?

count 7.68E+02

mean -6.48E-17

std 1.00E+00

min -1.14E+00

25% -8.45E-01

50% -2.51E-01

75% 6.40E-01

max 3.91E+00

Perhaps.

Hi , can you tell me the formula behind preprocessing.scale()?

Sure, learn more here:

http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.scale.html

And here:

https://en.wikipedia.org/wiki/Standard_score

While am training the data set am getting an accuracy around 100%.But when am testing am not getting the proper answer.what could be the reason?can you please help me with it

Sounds like you are overfitting the training dataset.

hai Mr. Jason Brownlee, I wanna ask about how to prints the values back in their original scale using normalizer

You can invert the scaling transforms, call scaler.invert_transform()

Hi Jason,

I tried to use standardized_X = preprocessing.scale(X).

I checked with print(np.mean(standardized_X[:,0])) but mean is not zero (for any of the four columns) although standard deviation is one. Am I doing something incorrectly.

Please suggest.

I’m surprised. I would expect it to be zero, perhaps confirm that you have not introduced a bug or typo?

If i have target values in different range for prediction using regression with deep neural network will it be helpful to get better accuracy by doing normalization of target values?If yes, then which technique i should use for that.

Yes, perhaps try normalize and standardize and see which results in better skill compared to no rescaling.

When to normalize and when to standardize ??

Normalize when the data variables have different units.

Standardize when a variable has a gaussian distribution.

i have a dummy question;

there were 2 lines in your code.

X = iris.data

y = iris.target

how does X and Y know what the dependent and independent variables are? Will this work on my own dataset, without me having to tell it ( doubt it).

Thanks

I am choosing the dependent/independent based on my knowledge of the problem.

Perhaps this post will help you with your problem:

http://machinelearningmastery.com/how-to-define-your-machine-learning-problem/