Test-Time Augmentation For Tabular Data With Scikit-Learn

Last Updated on

Test-time augmentation, or TTA for short, is a technique for improving the skill of predictive models.

It is typically used to improve the predictive performance of deep learning models on image datasets where predictions are averaged across multiple augmented versions of each image in the test dataset.

Although popular with image datasets and neural network models, test-time augmentation can be used with any machine learning algorithm on tabular datasets, such as those often seen in regression and classification predictive modeling problems.

In this tutorial, you will discover how to use test-time augmentation for tabular data in scikit-learn.

After completing this tutorial, you will know:

  • Test-time augmentation is a technique for improving model performance and is commonly used for deep learning models on image datasets.
  • How to implement test-time augmentation for regression and classification tabular datasets in Python with scikit-learn.
  • How to tune the number of synthetic examples and amount of statistical noise used in test-time augmentation.

Discover data cleaning, feature selection, data transforms, dimensionality reduction and much more in my new book, with 30 step-by-step tutorials and full Python source code.

Let’s get started.

Test-Time Augmentation With Scikit-Learn

Test-Time Augmentation With Scikit-Learn
Photo by barnimages, some rights reserved.

Tutorial Overview

This tutorial is divided into three parts; they are:

  1. Test-Time Augmentation
  2. Standard Model Evaluation
  3. Test-Time Augmentation Example

Test-Time Augmentation

Test-time augmentation, or TTA for short, is a technique for improving the skill of a predictive model.

It is a procedure implemented when using a fit model to make predictions, such as on a test dataset or on new data. The procedure involves creating multiple slightly modified copies of each example in the dataset. A prediction is made for each modified example and the predictions are averaged to give a more accurate prediction for the original example.

TTA is often used with image classification, where image data augmentation is used to create multiple modified versions of each image, such as crops, zooms, rotations, and other image-specific modifications. As such, the technique results in a lift in the performance of image classification algorithms on standard datasets.

In their 2015 paper that achieved then state-of-the-art results on the ILSVRC dataset titled “Very Deep Convolutional Networks for Large-Scale Image Recognition,” the authors use horizontal flip test-time augmentation:

We also augment the test set by horizontal flipping of the images; the soft-max class posteriors of the original and flipped images are averaged to obtain the final scores for the image.

Very Deep Convolutional Networks for Large-Scale Image Recognition, 2015.

For more on test-time augmentation with image data, see the tutorial:

Although often used for image data, test-time augmentation can also be used for other data types, such as tabular data (e.g. rows and columns of numbers).

There are many ways that TTA can be used with tabular data. One simple approach involves creating copies of rows of data with small Gaussian noise added. The predictions from the copied rows can then be averaged to result in an improved prediction for regression or classification.

We will explore how this might be achieved using the scikit-learn Python machine learning library.

First, let’s define a standard approach for evaluating a model.

Want to Get Started With Data Preparation?

Take my free 7-day email crash course now (with sample code).

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

Download Your FREE Mini-Course

Standard Model Evaluation

In this section, we will explore the typical way of evaluating a machine learning model before we introduce test-time augmentation in the next section.

First, let’s define a synthetic classification dataset.

We will use the make_classification() function to create a dataset with 100 examples, each with 20 input variables.

The example creates and summarizes the dataset.

Running the example creates the dataset and confirms the number of rows and columns of the dataset.

This is a binary classification task and we will fit and evaluate a linear model, specifically, a logistic regression model.

A good practice when evaluating machine learning models is to use repeated k-fold cross-validation. When the dataset is a classification problem, it is important to ensure that a stratified version of k-fold cross-validation is used. As such, we will use repeated stratified k-fold cross-validation with 10 folds and 5 repeats.

We will enumerate the folds and repeats manually so that later we can perform test-time augmentation.

Each loop, we must define and fit the model, then use the fit model to make a prediction, evaluate the predictions, and store the result.

At the end, we can report the mean classification accuracy across all folds and repeats.

Tying this together, the complete example of evaluating a logistic regression model on the synthetic binary classification dataset is listed below.

Running the example evaluates the logistic regression using repeated stratified k-fold cross-validation.

Your specific results may differ given the stochastic nature of the learning algorithm. Consider running the example a few times,

In this case, we can see that the model achieved the mean classification accuracy of 79.8 percent.

Next, let’s explore how we might update this example to use test-time augmentation.

Test-Time Augmentation Example

Implementing test-time augmentation involves two steps.

The first step is to select a method for creating modified versions of each row in the test set.

In this tutorial, we will add Gaussian random noise to each feature. An alternate approach might be to add uniformly random noise or even copy feature values from examples in the test dataset.

The normal() NumPy function will be used to create a vector of random Gaussian values with a zero mean and small standard deviation. The standard deviation should be proportional to the distribution for each variable in the training dataset. In this case, we will keep the example simple and use a value of 0.02.

Given a row of data from the test set, we can create a given number of modified copies. It is a good idea to use an odd number of copies, such as 3, 5, or 7, as when we average the labels assigned to each later, we want to break ties automatically.

The create_test_set() function below implements this; given a row of data, it will return a test set that contains the row as well as “n_cases” modified copies, defaulting to 3 (so the test set size is 4).

An improvement to this approach would be to standardize or normalize the train and test datasets each loop and then use a standard deviation for the normal() that is consistent across features meaningful to the standard normal. This is left as an exercise for the reader.

The second setup is to make use of the create_test_set() for each example in the test set, make a prediction for the constructed test set, and record the predicted label using a summary statistic across the predictions. Given that the prediction is categorical, the statistical mode would be appropriate, via the mode() scipy function. If the dataset was regression or we were predicting probabilities, the mean or median would be more appropriate.

The test_time_augmentation() function below implements this; given a model and a test set, it returns an array of predictions where each prediction was made using test-time augmentation.

Tying all of this together, the complete example of evaluating the logistic regression model on the dataset using test-time augmentation is listed below.

Running the example evaluates the logistic regression using repeated stratified k-fold cross-validation and test-time augmentation.

Your specific results may differ given the stochastic nature of the learning algorithm. Consider running the example a few times.

In this case, we can see that the model achieved the mean classification accuracy of 81.0 percent, which is better than the test harness that does not use test-time augmentation that achieved an accuracy of 79.8 percent.

It might be interesting to grid search the number of synthetic examples created each time a prediction is made during test-time augmentation.

The example below explores values between 1 and 20 and plots the results.

Running the example reports the accuracy for different numbers of synthetic examples created during test-time augmentation.

Your specific results may differ given the stochastic nature of the learning algorithm. Consider running the example a few times.

Recall that we used three examples in the previous example.

In this case, it looks like a value of three might be optimal for this test harness, as all other values seem to result in lower performance.

A line plot of number of examples vs. classification accuracy is created showing that perhaps odd numbers of examples generally result in better performance than even numbers of examples.

This might be expected due to their ability to break ties when using the mode of the predictions.

Line Plot of Number of Synthetic Examples in TTA vs. Classification Accuracy

Line Plot of Number of Synthetic Examples in TTA vs. Classification Accuracy

We can also perform the same sensitivity analysis with the amount of random noise added to examples in the test set during test-time augmentation.

The example below demonstrates this with noise values between 0.01 and 0.3 with a grid of 0.01.

Running the example reports the accuracy for different amounts of statistical noise added to examples created during test-time augmentation.

Your specific results may differ given the stochastic nature of the learning algorithm. Consider running the example a few times.

Recall that we used a standard deviation of 0.02 in the first example.

In this case, it looks like a value of about 0.230 might be optimal for this test harness, resulting in a slightly higher accuracy of 81.2 percent.

A line plot of the amount of noise added to examples vs. classification accuracy is created, showing that perhaps a small range of noise around a standard deviation of 0.250 might be optimal on this test harness.

Line Plot of Statistical Noise Added to Examples in TTA vs. Classification Accuracy

Line Plot of Statistical Noise Added to Examples in TTA vs. Classification Accuracy

Why not use an oversampling method like SMOTE?

SMOTE is a popular oversampling method for rebalancing observations for each class in a training dataset. It can create synthetic examples but requires knowledge of the class labels which does not make it easy for use in test-time augmentation.

One approach might be to take a given example for which a prediction is required and assume it belongs to a given class. Then generate synthetic samples from the training dataset using the new example as the focal point of the synthesis, and classify them. This is then repeated for each class label. The total or average classification response (perhaps probability) can be tallied for each class group and the group with the largest response can be taken as the prediction.

This is just off the cuff, I have not actually tried this approach. Have a go and let me know if it works.

Further Reading

This section provides more resources on the topic if you are looking to go deeper.

Tutorials

APIs

Summary

In this tutorial, you discovered how to use test-time augmentation for tabular data in scikit-learn.

Specifically, you learned:

  • Test-time augmentation is a technique for improving model performance and is commonly used for deep learning models on image datasets.
  • How to implement test-time augmentation for regression and classification tabular datasets in Python with scikit-learn.
  • How to tune the number of synthetic examples and amount of statistical noise used in test-time augmentation.

Do you have any questions?
Ask your questions in the comments below and I will do my best to answer.

Get a Handle on Modern Data Preparation!

Data Preparation for Machine Learning

Prepare Your Machine Learning Data in Minutes

...with just a few lines of python code

Discover how in my new Ebook:
Data Preparation for Machine Learning

It provides self-study tutorials with full working code on:
Feature Selection, RFE, Data Cleaning, Data Transforms, Scaling, Dimensionality Reduction, and much more...

Bring Modern Data Preparation Techniques to
Your Machine Learning Projects


See What's Inside

20 Responses to Test-Time Augmentation For Tabular Data With Scikit-Learn

  1. kamal June 2, 2020 at 12:52 am #

    sir is we apply test time augmentation after optimization technique .for eg after hyper-parameter optimization of deep learning

    • Jason Brownlee June 2, 2020 at 6:18 am #

      Yes, it used with a fit model. Not during training.

  2. kimmie June 3, 2020 at 12:17 am #

    sir is test time augmentation is used with deep learning model

  3. sukhpal June 3, 2020 at 12:38 am #

    sir is u have papers on test time augmentation

  4. kamal June 4, 2020 at 10:00 pm #

    sir please provide test time augmentation on tabular data with deep learning.

    • Jason Brownlee June 5, 2020 at 8:10 am #

      Thanks for the suggestion.

      You can adapt the above examples directly for use with deep learning models.

  5. Osama June 6, 2020 at 11:33 pm #

    I understand test time augmentation but I need to understand how to apply oversampling in augmentation in other research

  6. Osama June 8, 2020 at 9:12 pm #

    I have a paper in breast cancer the author applying augmentation. I don’t know how the author apply it on the dataset.

  7. Parthiv June 9, 2020 at 2:40 am #

    Posting image specific techniques for numeric dataset is of great help.

    Is it possible to use augmentation on one-class numerical training dataset to generate the other class and then apply ML algorithms on test dataset with two class.

  8. Osama June 9, 2020 at 8:35 am #

    It has no email contact

    • Jason Brownlee June 9, 2020 at 1:19 pm #

      Perhaps search for the author via google.

      • Osama June 11, 2020 at 7:53 am #

        OK thanks

  9. Anthony The Koala June 10, 2020 at 6:23 pm #

    Dr Jason,
    In the section headed “Standard Model Evaluation”, I wanted to count how many iterations were in the loop

    when I set RepeatedStratifiedIKFold’s n_splits and n_repeats.

    Setting n_splits=10,n_repeats=5:

    There were 50 iterations of the loop

    Changing the parameters to n_splits=100, n_repeats=5:

    There were 500 iterations.

    code to replicate:

    Why is count = n_iterations * n_repeat?
    I thought the loop counted the number of repeats.

    .
    Thank you,
    Anthony of Sydney

    • Jason Brownlee June 11, 2020 at 5:53 am #

      If there are 10 folds and 5 repeats, then we would expected folds * repeats or 500 iterations and in turn results.

      • Anthony The Koala June 11, 2020 at 10:09 am #

        Dear Dr Jason,
        Thank you for the reply. I understand why the number of iterations is no_of_folds*repeats.

        To paraphrase:
        We have a dataset. We split the dataset into k folds. That is we take k random samples from the dataset. For each fold we split the dataset into train and test samples. The train is used to train the model and the test is used to test the model.

        The “repeat” means repeating k folds “repeat” times.

        Hence the total number of iterations is no_of_folds*repeats.

        Source: subheading What is K-Fold Cross Validation?, https://medium.com/datadriveninvestor/k-fold-cross-validation-6b8518070833 .

        You may yourself, “…what is train_ix and test_ix?

        Answer: train_ix, is an array of indices from the selections from the set of train_X and set of train_y. Similarly test_ix is an array of indices from the selections of set of test_X and set of test_y.

        Thank you,
        Anthony of Sydney

Leave a Reply