pythontensorflowkeraskeras-tuner

Installing keras_tuner in a TensorFlow 2.5 environment


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:

import tensorflow as tf
import keras_tuner as kt
from tensorflow import keras
import os
import cv2
import pandas as pd
import numpy as np
from tensorflow.keras.utils import to_categorical
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split


f= pd.read_csv('CELLS_ALL.csv')
Labels= f['labels']
path_dir = 'C:\\Users\\user1\\PycharmProjects\\imageDataGen\\images\\'
img_all = []
for i in os.listdir(path_dir):
   img_sig = cv2.imread(path_dir+i)
   img_sig = cv2.resize(img_sig, (50, 50))
   img_all.append(img_sig)
x = np.array(img_all, dtype="float") / 255.0
y = Labels
le = LabelEncoder()
y = le.fit_transform(y)
y = to_categorical(y)
#print(labels)


(trainX, testX, trainY, testY) = train_test_split(x, y, test_size=0.25, random_state=42)

# for cnn images should me of shape (len(training,size,size, channel)

trainX= trainX.reshape(len(trainX),50,50,3)
testX = testX.reshape(len(testX),50,50,3)


def build_model(hp):
    model = keras.Sequential([
        keras.layers.Conv2D(
            filters=hp.Int('conv_1_filter', min_value=128, max_value=256, step=16),
            kernel_size=hp.Choice('conv_1_kernel', values=[3, 5]),
            activation='relu',
            input_shape=(50, 50, 3)
        ),
        keras.layers.Conv2D(
            filters=hp.Int('conv_2_filter', min_value=128, max_value=256, step=16),
            kernel_size=hp.Choice('conv_2_kernel', values=[3, 5]),
            activation='relu'
        ),
        keras.layers.Flatten(),
        keras.layers.Dense(
            units=hp.Int('dense_1_units', min_value=32, max_value=128, step=16),
            activation='relu'
        ),
        keras.layers.Dense(15, activation='softmax')
    ])

    model.compile(optimizer=keras.optimizers.Adam(hp.Choice('learning_rate', values=[1e-2, 1e-3])),
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])

    return model

tuner_search= kt.RandomSearch(build_model,
                          objective='val_accuracy',
                          max_trials=5,directory='tune',project_name="cnn model tunning")

My question is how can I install keras_tuner and use RandomSearch?


Solution

  • 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.