在 TensorFlow 2.5 环境中安装 keras_tuner

Installing keras_tuner in a TensorFlow 2.5 environment

我正在尝试使用 keras_tuner.RandomSearch 找到适合我的模型的最佳参数。 我使用以下命令在我的 anaconda 命令提示符中安装了 keras_tuner:

conda install -c conda-forge keras-tuner

然后我导入包如下: 将 keras_tuner 导入为 kt

但是当我调用 kt.RandomSearch 时,我收到以下错误消息:

tuner_search=kt.RandomSearch(build_model, AttributeError:部分初始化的模块 'keras_tuner' 没有属性 'RandomSearch'(很可能是由于循环导入)。

以下是我的代码:

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")

我的问题是如何安装 keras_tuner 和使用 RandomSearch

您可能有一个本地文件(当前文件),其中包含库(您尝试导入的模块)的确切名称,因此是循环引用,因为 Python 认为是一个模块)。

更改您 运行 代码所在的文件的名称(避免与 library/module 名称完全重叠的命名)并查看它是否有效。