keras-tuner | A Hyperparameter Tuning Library for Keras | Machine Learning library

 by   keras-team Python Version: 1.4.6 License: Apache-2.0

kandi X-RAY | keras-tuner Summary

kandi X-RAY | keras-tuner Summary

keras-tuner is a Python library typically used in Artificial Intelligence, Machine Learning, Deep Learning, Tensorflow, Keras applications. keras-tuner has no vulnerabilities, it has build file available, it has a Permissive License and it has high support. However keras-tuner has 4 bugs. You can install using 'pip install keras-tuner' or download it from GitHub, PyPI.

Import KerasTuner and TensorFlow:. Write a function that creates and returns a Keras model. Use the hp argument to define the hyperparameters during model creation. Initialize a tuner (here, RandomSearch). We use objective to specify the objective to select the best models, and we use max_trials to specify the number of different models to try.

            kandi-support Support

              keras-tuner has a highly active ecosystem.
              It has 2728 star(s) with 370 fork(s). There are 65 watchers for this library.
              There were 8 major release(s) in the last 6 months.
              There are 191 open issues and 256 have been closed. On average issues are closed in 171 days. There are 3 open pull requests and 0 closed requests.
              It has a negative sentiment in the developer community.
              The latest version of keras-tuner is 1.4.6

            kandi-Quality Quality

              keras-tuner has 4 bugs (0 blocker, 0 critical, 4 major, 0 minor) and 65 code smells.

            kandi-Security Security

              keras-tuner has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
              keras-tuner code analysis shows 0 unresolved vulnerabilities.
              There are 7 security hotspots that need review.

            kandi-License License

              keras-tuner is licensed under the Apache-2.0 License. This license is Permissive.
              Permissive licenses have the least restrictions, and you can use them in most projects.

            kandi-Reuse Reuse

              keras-tuner releases are available to install and integrate.
              Deployable package is available in PyPI.
              Build file is available. You can build the component from source.
              Installation instructions, examples and code snippets are available.
              keras-tuner saves you 4084 person hours of effort in developing the same functionality from scratch.
              It has 8680 lines of code, 597 functions and 69 files.
              It has high code complexity. Code complexity directly impacts maintainability of the code.

            Top functions reviewed by kandi - BETA

            kandi has reviewed keras-tuner and discovered the below as its top functions. This is intended to give you an instant insight into keras-tuner implemented functionality, and help decide if they suit your requirements.
            • Connects the model
            • Context manager for conditional scope
            • Create a Choice instance
            • Return a fully qualified name
            • Runs a single trial
            • Builds the hyperparametric hyperparameters
            • Build and fit the given hyperparameters
            • Builds a keras model
            • Update a trial
            • Check if the hyperparameter is active
            • Populates the hyperparameters
            • Construct hyperparameters from keras_pb2
            • Register a transform
            • Converts the hyperparameters to a protobuf
            • End a trial
            • Fit the Gaussian model
            • Update the hyperparameters
            • Prints elapsed time
            • Return a list of the best fit models
            • Populates a trial space
            • Build the keras model
            • Write a path to a file
            • Run oracle search
            • Create a trial for the given trial
            • Populates a random trial allocation
            • Fills the Gaussian distribution with the given trial
            Get all kandi verified functions for this library.

            keras-tuner Key Features

            No Key Features are available at this moment for keras-tuner.

            keras-tuner Examples and Code Snippets

            PRiSM SampleRNN,Training,Hyperparameter Optimization
            Pythondot img1Lines of Code : 48dot img1License : Permissive (MIT)
            copy iconCopy
            python \
              --data_dir path/to/dataset \
              --num_epochs 20 \
              --frame_sizes 16 64 \
              --frame_sizes 32 128 \
              --batch_size 32 64 128 \
              --seq_len 512 1024 \
              --num_rnn_layers 2 4
            [Trial summary]
             |-Trial ID: b366a8c644b6b0a28ef0c37  
            Keras-tuner Tensorboard logger,Example
            Pythondot img2Lines of Code : 19dot img2License : Permissive (MIT)
            copy iconCopy
            # import this
            from kerastuner_tensorboard_logger import (
                setup_tb  # Optional
            tuner = Hyperband(
            Keras-tuner Tensorboard logger,Installation
            Pythondot img3Lines of Code : 1dot img3License : Permissive (MIT)
            copy iconCopy
            $ pip install kerastuner-tensorboard-logger
            How can i use tf.keras.callbacks.ModelCheckpoint in Keras Tuner?
            Pythondot img4Lines of Code : 27dot img4License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            hypermodel =
            # Retrain the model
  , label_train, epochs=best_epoch, validation_split=0.2)
            import os
            checkpoint_path = "training_1/cp.ckpt"
            checkpoint_dir = os.path.dirname(checkpoin
            Tensor's shape is not compatible with supplied shape, Error in Keras Tuner
            Pythondot img5Lines of Code : 9dot img5License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            # ...
            tuner = kt.Hyperband(
                        overwrite = True) # here
            # ...
            Tuning hyperparameters with Keras return different results depending on the method used
            Pythondot img6Lines of Code : 5dot img6License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            best_hp = tuner.get_best_hyperparameters()[0]
            model =
            Predicting a label of 5 different classes with tensorflow keras
            Pythondot img7Lines of Code : 32dot img7License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            outputs = tf.keras.layers.Dense(1, activation='sigmoid')(x)
            change your model compile code from
            How can I tune the optimization function with Keras Tuner?
            Pythondot img8Lines of Code : 15dot img8License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            hp_optimizer = hp.Choice('optimizer', values=['sgd', 'rmsprop', 'adam'])
            if hp_optimizer == 'sgd':
                optimizer = SGD(learning_rate=hp_lr)
            elif hp_optimizer == 'rmsprop':
                optimizer = RMSprop(learning_rate=hp_lr)
            elif hp_optimzier == 
            Keras Hyperband Search Using Directory Iterator
            Pythondot img9Lines of Code : 5dot img9License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            I need some help setting up Keras-Tuner with Celeb_a dataset using Spyder
            Pythondot img10Lines of Code : 104dot img10License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            def get_annotation(fnmtxt, verbose=True):
            if verbose:
                print("_" * 70)
            rfile = open(fnmtxt, 'r')
            texts ="\n")
            columns = np.array(texts[1].split(" "))
            columns = columns[columns != ""]

            Community Discussions


            Error regarding "accuracy" in hyper-parameter tuning using Keras-tuner
            Asked 2021-Nov-09 at 14:50

            My original MLP model is as follows:



            Answered 2021-Oct-17 at 07:00

            I can imagine you are getting this warning and error because you have to use exactly the same metric from your model and Keras Tuner model in your RandomSearch target, which is categorical_accuracy. So, perhaps, try:



            Keras Sklearn Tuner module 'sklearn' has no attribute 'pipeline'
            Asked 2021-Sep-10 at 17:18
            from sklearn import ensemble
            from sklearn import linear_model
            def build_model(hp):
                model_type = hp.Choice('model_type', ['random_forest', 'ridge'])
                if model_type == 'random_forest':
                    with hp.conditional_scope('model_type', 'random_forest'):
                        model = ensemble.RandomForestClassifier(
                            n_estimators=hp.Int('n_estimators', 10, 50, step=10),
                            max_depth=hp.Int('max_depth', 3, 10))
                elif model_type == 'ridge':
                    with hp.conditional_scope('model_type', 'ridge'):
                        model = linear_model.RidgeClassifier(
                            alpha=hp.Float('alpha', 1e-3, 1, sampling='log'))
                    raise ValueError('Unrecognized model_type')
                return model
            tuner = kt.tuners.Sklearn(
                        objective=kt.Objective('score', 'max'),
            X, y = datasets.load_iris(return_X_y=True)
            X_train, X_test, y_train, y_test = model_selection.train_test_split(
                X, y, test_size=0.2)
  , y_train)
            best_model = tuner.get_best_models(num_models=1)[0]


            Answered 2021-Sep-10 at 17:18

            Adding import sklearn.pipeline would temporarily fix the problem.

            This is a very recent issue and will be fixed in the next release.

            You can find more about it here



            Installing keras_tuner in a TensorFlow 2.5 environment
            Asked 2021-Aug-26 at 09:48

            I'm trying to use keras_tuner.RandomSearch to find the best parameters that fit my model. I installed keras_tuner in my anaconda command prompt using the following command:

            conda install -c conda-forge keras-tuner

            I then imported the package as follows: import keras_tuner as kt

            but when I call kt.RandomSearch, I got the following error message:

            tuner_search= kt.RandomSearch(build_model, AttributeError: partially initialized module 'keras_tuner' has no attribute 'RandomSearch' (most likely due to a circular import).

            following is my code:



            Answered 2021-Aug-26 at 09:48

            It is likely that you have a local file (the current one) with the exact name of the library (the module you are trying to import), hence the circular reference, since Python thinks is is a module).

            Change the name of the file in which you run the code (avoid namings which overlap perfectly with the library/module names) and see if it works.



            Data cardinality is ambiguous: x sizes: 25838 y sizes: 3589 Make sure all arrays contain the same number of samples
            Asked 2021-Jun-27 at 18:25

            I am trying to use hyperparameter optimization in FER2013 test set but I am not able to overcome this problem ...any help or suggestion.



            Answered 2021-Jun-27 at 18:25

            I just banged my head for 10 straight hours for a silly mistake

            wrong :,X_test,epochs=3,validation_split=0.1) correct:,y_train,epochs=3,validation_split=0.1)



            InvalidArgumentError: logits and labels must have the same first dimension, got logits shape [1,10] and labels shape [40]
            Asked 2021-Apr-14 at 19:30

            I'm using Keras-Tuner to auto-identify the best parameters for my CNN. I am using Celeb_a dataset.

            you can find the code I am using here When I try to run it I get the error below.

            InvalidArgumentError: logits and labels must have the same first dimension, got logits shape [1,10] and labels shape [40] [[node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits (defined at C:\Users\admin-sepr\anaconda3\envs\tf\lib\site-packages\kerastuner\engine\ ]] [Op:__inference_train_function_953]

            I have seen in other places that this could be down to using loss="categorical_crossentropy", when I compile the code and they recomended to try loss="sparse_categorical_crossentropy", instead.

            when I do this I get the following error.

            InvalidArgumentError: logits and labels must be broadcastable: logits_size=[64,380192] labels_size=[64,40] [[node categorical_crossentropy/softmax_cross_entropy_with_logits (defined at C:\Users\admin-sepr\anaconda3\envs\tf\lib\site-packages\kerastuner\engine\ ]] [Op:__inference_train_function_6830]

            The function call stack is the following for both errors.



            Answered 2021-Apr-14 at 19:30

            It looks like your data you have loaded from the Celeb_A dataset is not compatible with the model that you are trying to train. From just scanning the code it looks like you need to change the number of nodes in your output dense layer. This number (which you currently have at 10 nodes) should match the number of labels you expect to predict. From the error, it looks like there are 40 labels that you are predicting but the model thinks there are only 10.

            My best guess is to keep your loss as categorical cross-entropy and change your output dense layer to Dense(40) rather than Dense(10).



            I need some help setting up Keras-Tuner with Celeb_a dataset using Spyder
            Asked 2021-Apr-01 at 20:00

            I'm trying to come up with a way to use Keras-Tuner to auto-identify the best parameters for my CNN. I am using Celeb_a dataset

            I tried a similar project where I used fashion_mnist and this worked perfectly but my experience with python isn't enough to do what I want to achieve. When I tried with fashion_mnist I managed to create this table of results

            My code is here.

            I am hoping to produce a similar table using the Celeb_a dataset. This is for a report I'm doing for college. In the report, my college used AWS Rekognition to produce the table below.

            I am hoping to be able to train the data so I can save this model to a pickle and generate a similar table of results to compare them.

            Any recommendations on how to approach this? My queries at the moment are:

            1. How to load the dataset correctly?
            2. how can i train the model to give me accuracy on "Moustache", "Beard", "Emotion" (like on the table of results above)

            I tried loading the data using:



            Answered 2021-Apr-01 at 20:00

            I managed to do this by creating a function to collect all annotations like this:



            Keras-Tuner RuntimeError
            Asked 2021-Feb-21 at 09:13

            I'm getting following error and I'm not able to figure out why:

            RuntimeError: Model-building function did not return a valid Keras Model instance, found (, )

            I have read the answers here and here which seem to telling to import keras from tensorflow instead of stand alone keras which I'm doing but still getting the error. I would very much appreciate your help in figuring this out. Below is my entire code:



            Answered 2021-Feb-21 at 09:13

            RuntimeError: Model-building function did not return a valid Keras Model instance, found (, )

            (, )

            As you can see this a tuple of two Keras Model instance. This is output of create_autoencoder(hp, input_dim, output_dim).



            'extras_require' must be a dictionary whose values are strings or lists of strings containing valid project/version requirement specifiers
            Asked 2020-Dec-17 at 18:42

            I have a which contains the following:



            Answered 2020-Sep-01 at 13:41

            You can only use PEP 508 - Dependency specification for Python Software Packages requirements. git:// is not valid syntax according to that standard.

            setuptools does accept the name@ url direct reference syntax:



            SyntaxError: positional argument follows keyword argument in CNN model
            Asked 2020-Dec-09 at 21:31

            I am trying to make a CNN model and I get a the following error



            Answered 2020-Dec-09 at 17:37
            keras.layers.MaxPooling2D(pool_size = (2,2), padding= "same"),



            Tune a pre-existing model with Keras Tuner
            Asked 2020-Sep-23 at 15:24

            I am looking at Keras Tuner as a way of doing hyperparameter optimization, but all of the examples I have seen show an entirely fresh model being defined. For example, from the Keras Tuner Hello World:



            Answered 2020-Sep-23 at 15:24

            Indeed this is possible, as this GitHub issue makes clear...

            However rather than passing the hp object through the hyperparameters arg to the Tuner, instead I override the Tuner run_trial method in the manner suggested here.


            Community Discussions, Code Snippets contain sources that include Stack Exchange Network


            No vulnerabilities reported

            Install keras-tuner

            KerasTuner requires Python 3.6+ and TensorFlow 2.0+.


            Getting started with KerasTunerKerasTuner developer guidesKerasTuner API reference
            Find more information at:

            Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items

            Find more libraries
          • PyPI

            pip install keras-tuner

          • CLONE
          • HTTPS


          • CLI

            gh repo clone keras-team/keras-tuner

          • sshUrl


          • Stay Updated

            Subscribe to our newsletter for trending solutions and developer bootcamps

            Agree to Sign up and Terms & Conditions

            Share this Page

            share link