python - TensorFlow fit 给出了 TypeError : Cannot clone object error

标签 python conv-neural-network tensorflow2.x

我正在使用基本的 CNN 模型对我的数据进行分类。我的输入数据的维度是 (325, 20, 244,244)。我使用的代码如下:

model = Sequential()
model.add(Dense(2, activation='relu', input_shape=X_train.shape[1:]))
model.add(Dense(2, activation='sigmoid'))

optimizer = ['SGD', 'RMSprop', 'Adagrad', 'Adadelta', 'Adam', 'Adamax', 'Nadam']
epochs = [10, 50, 100]
param_grid = dict(epochs=epochs, optimizer=optimizer)

model.compile(loss='binary_crossentropy', metrics=['accuracy'])
grid = GridSearchCV(estimator=model, param_grid=param_grid, scoring='accuracy', n_jobs=-1, refit='boolean')
grid_result = grid.fit(X_train, Y_train, validation_data=(X_test, Y_test))
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))

我得到的输出是:
grid_result = grid.fit(X_train, Y_train, validation_data=(X_test, Y_test))

Traceback (most recent call last):

  File "<ipython-input-16-bb553189f3ee>", line 1, in <module>
    grid_result = grid.fit(X_train, Y_train, validation_data=(X_test, Y_test))

  File "C:\Users\Student\Anaconda3\lib\site-packages\sklearn\model_selection\_search.py", line 633, in fit
    base_estimator = clone(self.estimator)

  File "C:\Users\Student\Anaconda3\lib\site-packages\sklearn\base.py", line 60, in clone
    % (repr(estimator), type(estimator)))

TypeError: Cannot clone object '<tensorflow.python.keras.engine.sequential.Sequential object at 0x0000025993610B08>' (type <class 'tensorflow.python.keras.engine.sequential.Sequential'>): it does not seem to be a scikit-learn estimator as it does not implement a 'get_params' methods.

任何人都可以告诉我代码有什么问题以及如何更正。

最佳答案

在此链接中:Tensorflow Keras wrapper for sklearnKeras wrapper

您可以看到 tensorflow keras 有一个包装器,用于将 keras 模型与 sklearn 一起使用。

所以,你必须使用 KerasClassifier(build_fn=None, **sk_params)其中 build_fn 应该是一个函数,您可以在其中对模型进行编码,并且该函数采用您想要调整的参数。

所以你应该像这样编码你的模型:

def getModel(optimizer):
    model = Sequential()
    model.add(Dense(2, activation='relu', input_shape=X_train.shape[1:]))
    model.add(Dense(2, activation='sigmoid'))
    model.compile(optimizer=optimizer , loss = tf.losses.categorical_crossentropy , metrics=['accuracy'])
    return model


optimizer = ['SGD', 'RMSprop', 'Adagrad', 'Adadelta', 'Adam', 'Adamax', 'Nadam']
epochs = [10, 50, 100]

param_grid = dict(epochs=epochs, optimizer=optimizer)

Kmodel = KerasClassifier(build_fn=getModel, verbose=1)
grid = GridSearchCV(estimator=Kmodel, param_grid=param_grid, scoring='accuracy', n_jobs=-1, refit='boolean')
grid_result = grid.fit(X_train, Y_train)

有关 mnist 上 KerasClassifier 的编码示例,您可以访问 github

关于python - TensorFlow fit 给出了 TypeError : Cannot clone object error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60350049/

相关文章:

python - 将随机日期添加到时间戳值存储在列中并将结果保存在新列中

image-processing - 如何在对象定位中执行数据扩充

python - 如何在 Tensorflow 2.0 中获得其他指标(不仅仅是准确性)?

tensorflow - 错误: Illegal instruction (core dumped) - tensorflow==2. 1.0

neural-network - PyTorch 中是否有将卷积转换为全连接网络形式的函数?

TensorFlow 2.3 GPU - InvalidArgumentError : assertion failed: [0] [Op:Assert] name: EagerVariableNameReuse

python将字符串转换为运算符

c# - 如何在 C# 中将变量参数传递给内部方法

python - 解析除某些属性值之外的 float 和返回路径

python - ValueError : `decode_predictions` expects a batch of predictions (i. e。形状的二维数组(样本,1000))。找到形状为 : (1, 的数组 7)