问题描述
我一直在使用hyperas和keras使用以下代码获取“ NoneType”对象没有属性“ evaluate”错误。 任何帮助,将不胜感激!
错误是AttributeError:“ NoneType”对象没有属性“ evaluate”
这是我的第一个keras and 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'
1楼
好的,看来您的optim.minimize
函数未返回模型。
查看 ,我发现默认情况下best_model
= None
,如果您没有进行有效的trials
那么它将一直保持到最后。
我对Keras的了解不多,所以Hyperas在Trials()
中的作用超出了我的了解。
检查该函数,看看它会输出什么,或者是否需要任何输入来生成输出等。
祝好运。
2楼
好像您在create_model()中运行实验,然后将模型扔掉了。 如果您返回模型,则可以解决您的问题。 尝试:
out={'loss':-acc,'score':score,'status':STATUS_OK, 'model': network}