New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
hyperas on LSTM #1
Comments
Hi, Thanks for reporting this. Would you mind sharing the complete example, so I can examine? |
I suspect you get the error, because you don't properly wrap your model into a function. If, in your example, you pass
which is clearly lacking def return_full_model_here():
import everything_you_need_for_the_model
X = ...
y = ...
model = Sequential()
model.add(LSTM(input_dim=388, output_dim=300, return_sequences=False))
....
model.add(Activation("linear"))
model.compile(loss="mean_squared_error", optimizer="rmsprop")
model.fit(X, y)
return {'loss': model_metric_to_minimize, 'status': STATUS_OK} You need all this, since the model with double brackets dropped-in clearly isn't valid code in any sense and all hyperas does is tell hyperopt what to plug in, so to make this an actual keras model. Therefore the function wrapper. I hope this makes sense, probably I should update the documentation accordingly. |
This is the code i have which is throwing error. def keras_model():
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from keras.callbacks import EarlyStopping, ModelCheckpoint
model = Sequential()
model.add(LSTM(input_dim=388, output_dim=300, return_sequences=False))
model.add(Dropout({{uniform(0, 1)}}))
model.add(Dense(output_dim=1))
model.add(Activation("linear"))
model.compile(loss="mean_squared_error", optimizer="rmsprop")
early_stopping = EarlyStopping(monitor='val_loss', patience=4)
checkpointer = ModelCheckpoint(filepath='keras_weights.hdf5',
verbose=1,
save_best_only=True)
hist = model.fit(X_train, y_train,
batch_size={{choice([32, 64, 128])}},
#batch_size=128,
nb_epoch=1,
validation_split=0.08,
show_accuracy=True)
#callbacks=[early_stopping, checkpointer])
score = model.evaluate(X_test, y_test,
show_accuracy=True, verbose=0)
print('Test accuracy:', score[1])
return {'loss': -score[1], 'status': STATUS_OK}
if __name__ == '__main__':
best_run = optim.minimize(keras_model,
algo=tpe.suggest,
max_evals=10,
trials=Trials())
print(best_run) |
I have the same error as @parindam "OSError: [Errno 2] No such file or directory: './temp.pyc". I am using a virtualenv to run keras. And nothing fancy from the code. Do you have an idea ?? |
As I don't have access to your data, I modified the keras imdb lstm example and reused every component in your example. It works. Have a try at this: from __future__ import print_function
from hyperopt import Trials, STATUS_OK, tpe
from hyperas import optim
from hyperas.distributions import choice, uniform
def keras_model():
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.embeddings import Embedding
from keras.layers.recurrent import LSTM
from keras.datasets import imdb
from keras.callbacks import EarlyStopping, ModelCheckpoint
max_features = 20000
maxlen = 100
print('Loading data...')
(X_train, y_train), (X_test, y_test) = imdb.load_data(nb_words=max_features, test_split=0.2)
print(len(X_train), 'train sequences')
print(len(X_test), 'test sequences')
print("Pad sequences (samples x time)")
X_train = sequence.pad_sequences(X_train, maxlen=maxlen)
X_test = sequence.pad_sequences(X_test, maxlen=maxlen)
print('X_train shape:', X_train.shape)
print('X_test shape:', X_test.shape)
print('Build model...')
model = Sequential()
model.add(Embedding(max_features, 128, input_length=maxlen))
model.add(LSTM(128))
model.add(Dropout({{uniform(0, 1)}}))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='adam',
class_mode="binary")
early_stopping = EarlyStopping(monitor='val_loss', patience=4)
checkpointer = ModelCheckpoint(filepath='keras_weights.hdf5',
verbose=1,
save_best_only=True)
hist = model.fit(X_train, y_train,
batch_size={{choice([32, 64, 128])}},
# batch_size=128,
nb_epoch=1,
validation_split=0.08,
show_accuracy=True,
callbacks=[early_stopping, checkpointer])
score, acc = model.evaluate(X_test, y_test, show_accuracy=True, verbose=0)
print('Test accuracy:', acc)
return {'loss': -acc, 'status': STATUS_OK}
if __name__ == '__main__':
best_run = optim.minimize(keras_model,
algo=tpe.suggest,
max_evals=10,
trials=Trials())
print(best_run) |
I will publish the above as an example for hyperas. Other than that, I'm afraid right now I'm running out of ideas how to help you. |
@parindam your error might be related with
This might be the issue. Try to have a read here: http://keras.io/layers/recurrent/ |
I copy/paste your new example with LSTM and i have the following error.
|
@jesuisnicolasdavid it works for me. Make sure you use the latest |
keras 0.3.2 is recommended. Well, "works on my machine". I'm still puzzled why this won't work for you. |
Ok, i manage to get rid of the previous error with a lot of update. Now i am trying to run the CNN_LSTM example from keras and the error i get is : IndexError Traceback (most recent call last) code :
|
Again, this one works for me as well. I will add another example to address it soon. I really want to help, and trust you see that, but I'm not sure this is really the scope of what was issued originally. Any thoughts? |
For me, the first hyperas evaluation is working well, it is when it passes on the second one that it crashes (just after the print of the score and accuracy). Did you run it for at least two evaluations ? If it is the case, maybe i have another issue with some import. Thanks for the help! |
Next time, could you please provide the full stack trace? Thanks.
This indicates an error that arises from treating scalars as iterables. When you write
instead of
then
does not make sense. One of those classic copy and paste things I guess. |
I'm going to close the Q&A now. ;) |
That was a really bad error from me! Thanks for your answer and your help ! You are doing an amazing work! |
if I have a model not sequential, how can run hyperopt?? |
Hi,
I am using keras 0.3.2 and trying a simple LSTM model with hyperas.
But I get the following error. Anything wrong ?
Exception: Layer is not connected. Did you forget to set "input_shape"?
model = Sequential()
model.add(LSTM(input_dim=388, output_dim=300, return_sequences=False))
model.add(Dropout({{uniform(0, 1)}}))
model.add(Dense(output_dim=1))
model.add(Activation("linear"))
model.compile(loss="mean_squared_error", optimizer="rmsprop")
The text was updated successfully, but these errors were encountered: