通过使用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'
答案 0 :(得分:1)
好的,好像您的optim.minimize
函数没有返回模型。
查看library时,我发现best_model
默认为= None
,如果您没有输入有效的trials
,它将一直保留到最后。我对Keras的了解不多,所以Trials()
中的hyperas超出了我的理解范围。
检查该函数并查看其输出内容,或者是否需要任何输入以生成输出等。
祝你好运。
答案 1 :(得分:0)
您似乎在create_model()中运行实验,然后将模型扔掉了。如果您返回模型,则可以解决您的问题。试试:
out={'loss':-acc,'score':score,'status':STATUS_OK, 'model': network}