NameError: name 'result' is not defined
Before filing an issue, please make sure to tick the following boxes.
-
[ ] Make sure your issue hasn't been filed already. Use GitHub search or manually check the existing issues, also the closed ones. Also, make sure to check the FAQ section of our readme.
-
[ ] Install latest hyperas from GitHub: pip install git+git://github.com/maxpumperla/hyperas.git
-
[ ] Install latest hyperopt from GitHub: pip install git+git://github.com/hyperopt/hyperopt.git
-
[ ] We have continuous integration running with Travis and make sure the build stays "green". If, after installing test utilities with
pip install pytest pytest-cov pep8 pytest-pep8, you can't successfully runpython -m pytestthere's very likely a problem on your side that should be addressed before creating an issue. -
[ ] Create a gist containing your complete script, or a minimal version of it, that can be used to reproduce your issue. Also, add your full stack trace to that gist. In many cases your error message is enough to at least give some guidance.
I tried to implement Hyperas on my Keras ML model, however after all 50 epochs it dies showing the error message "NameError: name 'result' is not defined" while invoking "trials = Trials()" (details shown below). May I know what is the root cause of this? It really took me a lot of time running it...
Traceback (most recent call last):
File "Trimer_useful_life_Hyperas.py", line 160, in <module>
trials = Trials())
File "/home/hliu/.conda/envs/hliuPython/lib/python3.6/site-packages/hyperas/optim.py", line 69, in minimize
keep_temp=keep_temp)
File "/home/hliu/.conda/envs/hliuPython/lib/python3.6/site-packages/hyperas/optim.py", line 139, in base_minimizer
return_argmin=True),
File "/home/hliu/.conda/envs/hliuPython/lib/python3.6/site-packages/hyperopt/fmin.py", line 388, in fmin
show_progressbar=show_progressbar,
File "/home/hliu/.conda/envs/hliuPython/lib/python3.6/site-packages/hyperopt/base.py", line 639, in fmin
show_progressbar=show_progressbar)
File "/home/hliu/.conda/envs/hliuPython/lib/python3.6/site-packages/hyperopt/fmin.py", line 407, in fmin
rval.exhaust()
File "/home/hliu/.conda/envs/hliuPython/lib/python3.6/site-packages/hyperopt/fmin.py", line 262, in exhaust
self.run(self.max_evals - n_done, block_until_done=self.asynchronous)
File "/home/hliu/.conda/envs/hliuPython/lib/python3.6/site-packages/hyperopt/fmin.py", line 227, in run
self.serial_evaluate()
File "/home/hliu/.conda/envs/hliuPython/lib/python3.6/site-packages/hyperopt/fmin.py", line 141, in serial_evaluate
result = self.domain.evaluate(spec, ctrl)
File "/home/hliu/.conda/envs/hliuPython/lib/python3.6/site-packages/hyperopt/base.py", line 844, in evaluate
rval = self.fn(pyll_rval)
File "/home/hliu/07_Auto_Trimer_Formation/02_Trimer_LifeTime/temp_model.py", line 200, in keras_fmin_fnct
NameError: name 'result' is not defined
Here is my codes:
### Headers.
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from keras.utils.vis_utils import plot_model
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
from matplotlib import pyplot as plt
#from sklearn.cross_validation import train_test_split
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix
### For hyperparameter optimization.
from hyperopt import Trials, STATUS_OK, tpe
from keras.utils import np_utils
from hyperas import optim
from hyperas.distributions import choice, uniform
from autokeras.image.image_supervised import load_image_dataset
def data():
x_train, y_train = load_image_dataset(csv_file_path="./autoKeras_train/label.csv",
images_path="./autoKeras_train/")
print(x_train.shape)
print(y_train.shape)
x_test, y_test = load_image_dataset(csv_file_path="./autoKeras_test/label_test.csv",
images_path="./autoKeras_test/")
print(x_test.shape)
print(y_test.shape)
return x_train, y_train, x_test, y_test
def create_model():
### Hyperparameters of neural network model.
nb_train_samples = 2000
nb_validation_samples = 800
epochs = 50
batch_size = {{choice([16, 32, 48, 64])}}
### This is according to the data NanoFab generates.
img_width, img_height = 512, 560
### Define where training and validation data locate.
train_data_dir = 'data/train'
validation_data_dir = 'data/validation'
### Data augmentation configuration we will use for training
test_datagen = ImageDataGenerator(
rescale = 1. / 255,
rotation_range = 180,
width_shift_range = 0.2,
height_shift_range = 0.2,
brightness_range = (0.8, 1.2),
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True,
vertical_flip = True
)
train_datagen = ImageDataGenerator(
rotation_range = 180,
width_shift_range = 0.2,
height_shift_range = 0.2,
brightness_range = (0.8, 1.2),
rescale = 1. / 255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True,
vertical_flip = True
)
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size = (img_width, img_height),
batch_size = batch_size,
class_mode ='binary')
validation_generator = test_datagen.flow_from_directory(
validation_data_dir,
target_size = (img_width, img_height),
batch_size = batch_size,
class_mode = 'binary')
### Dimensions of images.
img_width, img_height = 512, 560
if K.image_data_format() == 'channels_first':
input_shape = (3, img_width, img_height)
else:
input_shape = (img_width, img_height, 3)
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape = input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(
{{choice([32, 64, 128])}}, (3, 3)
)
)
model.add(Activation({{choice(['sigmoid', 'relu'])}}))
model.add(MaxPooling2D(pool_size = (2, 2)))
model.add(Conv2D({{choice([32, 64, 128])}}, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size = (2, 2)))
model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout( {{uniform(0, 1)}} ))
model.add(Dense(1))
model.add(Activation({{choice(['sigmoid', 'relu'])}}))
### Save CNN model architecture as an image file.
plot_model(model, to_file = 'hyperas_model_plot.png', show_shapes = True, show_layer_names = True)
### Configure learning process.
# Before training a model, we need to configure the learning process, via "compile" method.
# Three arguments are received: An optimizer, a loss function and a list of metrics.
# Since we are handling a binary classification problem, we're using "rmsprop", "binary_crossentropy" and "accuracy".
model.compile(loss = 'binary_crossentropy',
optimizer = {{choice(['rmsprop', 'adam', 'sgd'])}},
metrics = ['accuracy'])
history = model.fit_generator(
train_generator,
### Integer or None. Total number of steps (batches of samples) before declaring one epoch finished
# and starting the next epoch. When training with input tensors such as TensorFlow data tensors,
# the default None is equal to the number of samples in your dataset divided by the batch size,
# or 1 if that cannot be determined.
steps_per_epoch = nb_train_samples // batch_size,
epochs = epochs,
validation_data = validation_generator,
### Only relevant if steps_per_epoch is specified. Total number of steps (batches of samples)
# to validate before stopping.
validation_steps = nb_validation_samples // batch_size,
)
#get the highest validation accuracy of the training epochs
validation_acc = np.amax(result.history['val_acc'])
print('Best validation acc of epoch:', validation_acc)
return {'loss': -validation_acc, 'status': STATUS_OK, 'model': model}
if __name__ == '__main__':
#train_generator, validation_generator = data()
best_run, best_model = optim.minimize(model = create_model,
data = data,
algo = tpe.suggest,
max_evals = 5,
trials = Trials())
X_train, Y_train, X_test, Y_test = data()
print("Evalutation of best performing model:")
print(best_model.evaluate(X_test, Y_test))
print("Best performing model chosen hyper-parameters:")
print(best_run)
### Save model.
model.save('Trimer_Keras_model_trimer_lifetime_Hyperas.h5')
history = model.fit_generator() need to be store in the same variable as validation_acc = np.amax(result.history['val_acc'])
in this case changes the code result = model.fit_generator()