'NoneType'对象在 keras 中没有属性'evaluate' hyperas 错误



我不断收到一个"NoneType"对象没有属性"评估"错误,使用以下代码使用 hyperas 和 keras。任何帮助将不胜感激!

错误是属性错误:"NoneType"对象没有属性"evaluate">

这是我的第一个 keras 和 hyperas 项目。

#First keras program
from keras.datasets import mnist
from keras import models
from keras import layers
from keras import optimizers
from keras.utils import to_categorical
from hyperas import optim
from hyperas.distributions import choice
from hyperopt import Trials, STATUS_OK, tpe
#Loading Data
#Train_images has shape (60000,28,28)
#Train_labels has shape (60000)
def data():
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
train_images = train_images.reshape((60000, 28 * 28))
train_images = train_images.astype('float32') / 255
test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
return train_images,train_labels,test_images,test_labels
#Defining Network and adding Dense Layers
#Compiling Network
def create_model(train_images,train_labels,test_images,test_labels):
network = models.Sequential()
network.add(layers.Dense({{choice([256,512,1024])}}, activation='relu', input_shape=(28 * 28,)))
network.add(layers.Dense(10, activation='softmax'))
network.compile(optimizer='rmsprop',loss='categorical_crossentropy',metrics=['accuracy'])
network.fit(train_images,
train_labels,
validation_split=0.33,
epochs=5,
batch_size=128)
score,acc = network.evaluate(train_images,train_labels,verbose=0)
print('Test accuracy:',acc)
out={'loss':-acc,'score':score,'status':STATUS_OK}
return out
if __name__ == '__main__':
best_run, best_model = optim.minimize(model=create_model,
data=data,
algo=tpe.suggest,
max_evals=1,
trials=Trials())
x_train, y_train, x_test, y_test = data()
# mnist_model=create_model(x_train,y_train,x_test,y_test)
print("Evaluation of best performing model:")
print(best_model.evaluate(x_test, y_test,verbose=0))
print("Best performing model chosen hyper-parameters:")
print(best_run)

以下是完整的回溯

Traceback (most recent call last):
File "C:/Users/anubhav/Desktop/Projects/chollet/keras_mnist_dense_hyperas.py", line 51, in <module>
print(best_model.evaluate(x_test, y_test,verbose=0))
AttributeError: 'NoneType' object has no attribute 'evaluate'

好的,似乎您的optim.minimize函数没有返回模型。

查看库,我发现默认情况下best_model= None,如果您没有输入有效的trials那么它将保持这种状态直到最后。我对 Keras 没有太多了解,所以 hyperas 在Trials()中做什么超出了我的知识范围。

检查该函数并查看它将输出什么,或者它是否需要任何输入来生成输出等。

祝你好运。

看起来你正在create_model((中运行实验,然后扔掉模型。如果您返回模型,这可能会解决您的问题。尝试:

out={'loss':-acc,'score':score,'status':STATUS_OK, 'model': network}

最新更新