SALE! Use code blackfriday for 40% off everything!
Hurry, sale ends soon! Click to see the full catalog.

How to Use AutoKeras for Classification and Regression

Last Updated on September 6, 2020

AutoML refers to techniques for automatically discovering the best-performing model for a given dataset.

When applied to neural networks, this involves both discovering the model architecture and the hyperparameters used to train the model, generally referred to as neural architecture search.

AutoKeras is an open-source library for performing AutoML for deep learning models. The search is performed using so-called Keras models via the TensorFlow tf.keras API.

It provides a simple and effective approach for automatically finding top-performing models for a wide range of predictive modeling tasks, including tabular or so-called structured classification and regression datasets.

In this tutorial, you will discover how to use AutoKeras to find good neural network models for classification and regression tasks.

After completing this tutorial, you will know:

  • AutoKeras is an implementation of AutoML for deep learning that uses neural architecture search.
  • How to use AutoKeras to find a top-performing model for a binary classification dataset.
  • How to use AutoKeras to find a top-performing model for a regression dataset.

Let’s get started.

  • Update Sep/2020: Updated AutoKeras version and installation instructions.
How to Use AutoKeras for Classification and Regression

How to Use AutoKeras for Classification and Regression
Photo by kanu101, some rights reserved.

Tutorial Overview

This tutorial is divided into three parts; they are:

  1. AutoKeras for Deep Learning
  2. AutoKeras for Classification
  3. AutoKeras for Regression

AutoKeras for Deep Learning

Automated Machine Learning, or AutoML for short, refers to automatically finding the best combination of data preparation, model, and model hyperparameters for a predictive modeling problem.

The benefit of AutoML is allowing machine learning practitioners to quickly and effectively address predictive modeling tasks with very little input, e.g. fire and forget.

Automated Machine Learning (AutoML) has become a very important research topic with wide applications of machine learning techniques. The goal of AutoML is to enable people with limited machine learning background knowledge to use machine learning models easily.

Auto-keras: An efficient neural architecture search system, 2019.

AutoKeras is an implementation of AutoML for deep learning models using the Keras API, specifically the tf.keras API provided by TensorFlow 2.

It uses a process of searching through neural network architectures to best address a modeling task, referred to more generally as Neural Architecture Search, or NAS for short.

… we have developed a widely adopted open-source AutoML system based on our proposed method, namely Auto-Keras. It is an open-source AutoML system, which can be downloaded and installed locally.

Auto-keras: An efficient neural architecture search system, 2019.

In the spirit of Keras, AutoKeras provides an easy-to-use interface for different tasks, such as image classification, structured data classification or regression, and more. The user is only required to specify the location of the data and the number of models to try and is returned a model that achieves the best performance (under the configured constraints) on that dataset.

Note: AutoKeras provides a TensorFlow 2 Keras model (e.g. tf.keras) and not a Standalone Keras model. As such, the library assumes that you have Python 3 and TensorFlow 2.3.0 or higher installed.

At the time of writing, you require a prerequisite library called keras-tuner to be installed manually. You can install this library as follows:

If things change again, as they often do with fast-moving open source projects, see the official installation instructions here:

Now we can instal AutoKeras.

To install AutoKeras, you can use Pip, as follows:

You can confirm the installation was successful and check the version number as follows:

You should see output like the following:

Once installed, you can then apply AutoKeras to find a good or great neural network model for your predictive modeling task.

We will take a look at two common examples where you may want to use AutoKeras, classification and regression on tabular data, so-called structured data.

AutoKeras for Classification

AutoKeras can be used to discover a good or great model for classification tasks on tabular data.

Recall tabular data are those datasets composed of rows and columns, such as a table or data as you would see in a spreadsheet.

In this section, we will develop a model for the Sonar classification dataset for classifying sonar returns as rocks or mines. This dataset consists of 208 rows of data with 60 input features and a target class label of 0 (rock) or 1 (mine).

A naive model can achieve a classification accuracy of about 53.4 percent via repeated 10-fold cross-validation, which provides a lower-bound. A good model can achieve an accuracy of about 88.2 percent, providing an upper-bound.

You can learn more about the dataset here:

No need to download the dataset; we will download it automatically as part of the example.

First, we can download the dataset and split it into a randomly selected train and test set, holding 33 percent for test and using 67 percent for training.

The complete example is listed below.

Running the example first downloads the dataset and summarizes the shape, showing the expected number of rows and columns.

The dataset is then split into input and output elements, then these elements are further split into train and test datasets.

We can use AutoKeras to automatically discover an effective neural network model for this dataset.

This can be achieved by using the StructuredDataClassifier class and specifying the number of models to search. This defines the search to perform.

We can then execute the search using our loaded dataset.

This may take a few minutes and will report the progress of the search.

Next, we can evaluate the model on the test dataset to see how it performs on new data.

We then use the model to make a prediction for a new row of data.

We can retrieve the final model, which is an instance of a TensorFlow Keras model.

We can then summarize the structure of the model to see what was selected.

Finally, we can save the model to file for later use, which can be loaded using the TensorFlow load_model() function.

Tying this together, the complete example of applying AutoKeras to find an effective neural network model for the Sonar dataset is listed below.

Running the example will report a lot of debug information about the progress of the search.

The models and results are all saved in a folder called “structured_data_classifier” in your current working directory.

The best-performing model is then evaluated on the hold-out test dataset.

Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

In this case, we can see that the model achieved a classification accuracy of about 82.6 percent.

Next, the architecture of the best-performing model is reported.

We can see a model with two hidden layers with dropout and ReLU activation.

AutoKeras for Regression

AutoKeras can also be used for regression tasks, that is, predictive modeling problems where a numeric value is predicted.

We will use the auto insurance dataset that involves predicting the total payment from claims given the total number of claims. The dataset has 63 rows and one input and one output variable.

A naive model can achieve a mean absolute error (MAE) of about 66 using repeated 10-fold cross-validation, providing a lower-bound on expected performance. A good model can achieve a MAE of about 28, providing a performance upper-bound.

You can learn more about this dataset here:

We can load the dataset and split it into input and output elements and then train and test datasets.

The complete example is listed below.

Running the example loads the dataset, confirming the number of rows and columns, then splits the dataset into train and test sets.

AutoKeras can be applied to a regression task using the StructuredDataRegressor class and configured for the number of models to trial.

The search can then be run and the best model saved, much like in the classification case.

We can then use the best-performing model and evaluate it on the hold out dataset, make a prediction on new data, and summarize its structure.

Tying this together, the complete example of using AutoKeras to discover an effective neural network model for the auto insurance dataset is listed below.

Running the example will report a lot of debug information about the progress of the search.

The models and results are all saved in a folder called “structured_data_regressor” in your current working directory.

The best-performing model is then evaluated on the hold-out test dataset.

Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

In this case, we can see that the model achieved a MAE of about 24.

Next, the architecture of the best-performing model is reported.

We can see a model with two hidden layers with ReLU activation.

Further Reading

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

Summary

In this tutorial, you discovered how to use AutoKeras to find good neural network models for classification and regression tasks.

Specifically, you learned:

  • AutoKeras is an implementation of AutoML for deep learning that uses neural architecture search.
  • How to use AutoKeras to find a top-performing model for a binary classification dataset.
  • How to use AutoKeras to find a top-performing model for a regression dataset.

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

Develop Deep Learning Projects with Python!

Deep Learning with Python

 What If You Could Develop A Network in Minutes

...with just a few lines of Python

Discover how in my new Ebook:
Deep Learning With Python

It covers end-to-end projects on topics like:
Multilayer PerceptronsConvolutional Nets and Recurrent Neural Nets, and more...

Finally Bring Deep Learning To
Your Own Projects

Skip the Academics. Just Results.

See What's Inside

45 Responses to How to Use AutoKeras for Classification and Regression

  1. Ramesh Ravula September 2, 2020 at 9:56 pm #

    Does AutoKeras/AutoML tell you which Neural Network Algorithm it chose. The above example doesn’t tell you which algorithm it found to give the best result.

    • Jason Brownlee September 3, 2020 at 6:07 am #

      Yes, it reports the model architecture. We show this in the above tutorial.

      • Mohammadreza September 3, 2020 at 10:39 pm #

        Dear jason.
        Can we use autokeras in a 1d cnn for time series classification?

        • Jason Brownlee September 4, 2020 at 6:31 am #

          Perhaps try it and see?

          • Tom October 26, 2020 at 8:14 am #

            Do you how to use 1d cnn layer with autokeras ? Is there a parameter to do that ?
            By default, autokeras is not using 1d cnn layers to build model right ?

            Thank you

          • Jason Brownlee October 26, 2020 at 8:51 am #

            1D CNNs are appropriate for sequence prediction problems, not simple classification and regression.

            Perhaps you can use autokeras for sequence prediction problems, I’m not sure off the cuff – I recommend checking the documentation.

  2. Debashis September 3, 2020 at 5:32 pm #

    Is it applying a grid search technology, to apply model one by one and find the best results?

  3. Berns Buenaobra September 4, 2020 at 7:42 am #

    Having a problem installing autokeras with Anaconda?

  4. Rahul Dokania September 4, 2020 at 7:20 pm #

    pip install git+https://github.com/keras-team/keras-tuner.git@1.0.2rc1

    need to install before installing autokeras

  5. dexter September 5, 2020 at 2:07 am #

    hello Jason,

    Do you have in mind to do an article about autokeras with rnnblock?
    https://autokeras.com/block/#rnnblock

  6. Jeff Doran September 5, 2020 at 8:53 am #

    Jason,

    You might want to update your autokeras installation example above. The current autokeras 1.0.8 requires keras-tuner 1.0.2rc1 to successfully install.

    pip install git+https://github.com/keras-team/keras-tuner.git@1.0.2rc1
    pip install autokeras

    This is directly from https://autokeras.com/install/.

  7. Martin September 8, 2020 at 6:34 pm #

    Hi Jason,

    I have an error with the AutoKeras for Classification scripts (the sonar dataset example).
    It looks like an issue with tensorfow. I have:

    NotFoundError: Failed to create a NewWriteableFile: .\structured_data_classifier\trial_4d05b06e9169e134eb46fa62f3778824\checkpoints\ep… : The system cannot find the path specified.
    ; No such process [Op:SaveV2]

    How could I fix this?

    Thank you for you help,
    Best,

    Martin

  8. Gilloux September 12, 2020 at 11:01 pm #

    I also have a proble with autokeras.
    the installation looks fine and I got exactly the same info as your “sudo pip show autokeras”
    I’ve tryed also to uninstall and reinstall with above suggestion (keras-tuner.git@1.0.2rc1), but this is not working.
    my error message is
    ImportError: cannot import name ‘StructuredDataClassifier’ from partially initialized module ‘autokeras’ (most likely due to a circular import) ….

    The error appears on line 5 of th escript : “from autokeras import StructuredDataClassifier

    Any Idea on how to move foward on such thing.

    My config Windows 10. Python 3.8.3. and all librairies such as tensorflow, keras, theano etc are working fine on other scripts.

    Thanks Gilles

  9. Anthony The Koala September 19, 2020 at 3:20 pm #

    Dear Dr Jason
    * I have installed the packages by installing by source. OK
    * Particularly followed the advice https://autokeras.com/install/ on installation and used a git bash command installation.
    * I followed the advice of the commenter to direct my output to a particular directory

    BACKGROUND INFORMATION – SKIP PLEASE TO BOTTOM OF THIS COMMENT FOR QUESTIONS. THANK YOU.

    RESULT – both programs took a ‘long’ time to complete. I don’t know if it is the stochastic nature of the algorithm returning different results.

    First program – comparing my results with your results
    My accuracy = 0.783, your accuracy 0.826
    I ran this program twice and got a lower accuracy than your model

    No of params: mine 3162, yours 147313

    Second program
    I also ran the second program and compared the results of my running and your running.
    MAE – very similar between my running and your running, 24.663 cf 24.496

    BUT the # params were significantly different

    Conclusions:
    * First program, I ran a few times and my accuracy was about 0.77 compared to your 0.8+
    * In the first program, the # params was significanly different in magnitude.

    * Second program very similar result, BUT # params significantly different.

    In addition:
    * I ran the second program on a command line instead of IDE. I observed that there was CUDA info. Yes my GPU is NVidia, I did not have a CUDA software and python wrappers installed – my machine is nearly 10 years old.
    * Further to that, I only installed Tensorflow without GPU.

    **Questions:**
    * First program, why I frequency achieved an accuracy of 0.77+ compared to your 0.8+ accuracy.
    * Why I got significantly different # params.
    * Second program produced similar result to yours. BUT # params significantly different.
    * Would having CUDA software and Tensorflow for CUDA make the program run faster?

    Thank you,
    Anthony of Sydney

  10. Anthony The Koala September 20, 2020 at 11:55 am #

    Dear Dr Jason,
    Thank you,
    Anthony of Sydney

  11. Anthony The Koala September 20, 2020 at 8:31 pm #

    Dear Dr Jason,
    I did some further experimentation on the first program involving the StructuredDataClassifier.

    In the first example,you did a prediction with variable ‘row’.

    I wanted to see what happens when predicting the values using X_test.

    In sum, whether yhat is a float or integer, the correlation between y_test and yhat (whether decimal or float) is not that strong at 0.62. This is despite the accuracy of the model being 0.811.

    Yet when we predict using X_train:

    The correlation between the training Y and the fitted yhat5 is 0.879

    Even though the length of y_test is 0.33* len(y), why is the correlation higher at 0.88 with the test y_train and not so with the test y_test with correlation 062?

    Thank you,
    Anthony of Sydney

  12. Steve September 28, 2020 at 7:59 pm #

    Great API, many thanks for drawing our attention to this.
    Unfortunately, it seems that the authors have excluded the possibility of using sample weights for the training, which are otherwise smoothly integrated into Keras. I tried to do it by passing weight matrices via **kwargs and also by feeding in weighted data using the TF Datasets objects, but none of them worked. A closer look at the Autokeras source code revealed that it was purposely written without sample weighting in mind. I hope the authors will consider adding this functionality in future releases. Or am I missing something here?

    • Jason Brownlee September 29, 2020 at 5:34 am #

      Sorry to hear that.

      Perhaps try posting the problem as an issue on the github project to make the authors aware?

  13. Keyvan September 28, 2020 at 8:33 pm #

    Hi Dr. Brownlee,

    I am trying to perform regression on a dataframe using Autokeras. I wonder if I need to scale the train and test dataset after splitting them?

    Thanks,
    Keyvan

  14. repore October 8, 2020 at 1:59 pm #

    Thank you for your kind explanation about autokeras. I have a question about model which is searched by autokeras. I found best performance model with 300 tries via autokeras. do I have to train this model again with my dataset? I don’t know this model can be used directly to treat my problem. how can I get further steps for my problem with this model? I’m new one in this area, so I might have basic questions. I look forward to hearing from you. Thank you!

  15. Vivek Parekh October 14, 2020 at 9:36 pm #

    Hi Jason,

    I would like to know how can I get network configuration from Hdf5 file here as Autokeras thrown an architecture with custom layer so is it possible to manuallly recreate architecture which autokeras proposes as best architecture. If it used by built_in layers then we can get it from get_config() function but here it’s custom layer. Do you have any idea about that?

    Thanks for nice article.

    • Jason Brownlee October 15, 2020 at 6:09 am #

      I’m not sure off hand, perhaps experiment and discover how to solve it.

  16. George October 22, 2020 at 4:35 pm #

    Hi Jason,
    AutoKeras not working for predict_proba? Is there any work around
    Thanks

    • Jason Brownlee October 23, 2020 at 6:03 am #

      Call predict() as it will return probabilities directly.

      • George October 26, 2020 at 4:47 pm #

        Hi Jason, Actually AutoKeras returning as
        [0.],
        [0.],
        [0.],
        [1.],
        [1.],
        [1.],
        [0.]
        Its not returning probabilities for predict() function
        Thanks

        • Jason Brownlee October 27, 2020 at 6:41 am #

          Interesting.

          • George October 30, 2020 at 12:12 pm #

            Yes, Actually if we do prediction after exporting the model it returns probabiility
            model1.fit(x,y)
            model1.predict -> returns class
            model_export = model1..export_model()
            model_export.predict -> return probability
            Thanks

          • Jason Brownlee October 30, 2020 at 1:23 pm #

            Nice!

  17. susanne November 4, 2020 at 12:56 am #

    Dear Jason, thanks for the tutorial.

    Could you please, help, why I get NaN values for my loss?

    I tried literally everythin I googled, from checking the zero values in my data, normalizing data, changing activation, changing type of loss, but still, no result.

    Thank you for reply.

    • Jason Brownlee November 4, 2020 at 6:43 am #

      Scale the data, and confirm that the data is indeed scaled prior to fitting the model.
      Also confirm you have no nan in the raw data.

  18. Sivaramakrishnan S November 24, 2020 at 5:53 pm #

    Dear Jason, I have been a dormant beneficiary from many of your posts.

    I have couple of doubts, could you please help me on that?

    1. is it required to do normalization of features before using AutoKeras or AutoKeras takes care of it? If i do normalization myself before feeding it into AutoKeras, would it have any impacts on the results?

    2. I have a usecase where i have to predict 2 target variables (both are categorical), with your article, i was able to predict one variable. How do i predict two categorical variables from same input data simultaneously using StructuredDataClassifier or any other means of AutoKeras?

    Thank in Advance

    • Jason Brownlee November 25, 2020 at 6:41 am #

      Thanks.

      Yes, that is a good idea.

      Perhaps try one model per variable?
      Perhaps try a multi-output model?
      Perhaps try a model with one submodel head per output.

Leave a Reply