pythontensorflowkeraslstm

No module named 'keras.wrappers'


I have this code on google colab which allows me to optimise an LSTM model using gridsearchCV, but recently an error message has appeared:

ModuleNotFoundError: No module named 'keras.wrappers'.

is there another module other than 'keras.wrappers' that allows the code to be restarted?

Code:

from keras.layers import Dense, LSTM, Dropout
from keras import optimizers

from sklearn.model_selection import GridSearchCV
from keras.wrappers.scikit_learn import KerasRegressor

def create_model(unit, dropout_rate, lr ):
 model=Sequential()
 model.add(LSTM(unit,return_sequences=True, input_shape=(1,5)))
 model.add(Dropout(dropout_rate))
 model.add(LSTM(unit))
 model.add(Dropout(dropout_rate))
 model.add(Dense(1))
 adam= optimizers.Adam(lr)
 model.compile(optimizer=adam, loss='mean_squared_error')

 return model

my_regressor = KerasRegressor(build_fn=create_model, verbose=2)

grid_param_LSTM = {
    'unit':   [50, 70, 120],
    'batch_size': [12, 24, 48],
    'epochs': [200],
    'lr': [0.001, 0.01, 0.1],
    'dropout_rate':[0.1, 0.2, 0.3]
}

grid_GBR = GridSearchCV(estimator=my_regressor, param_grid = grid_param_LSTM, scoring = 'neg_root_mean_squared_error',  cv = 2)
grid_GBR.fit(X_train, y_train)

print("Best: %f using %s" % (grid_GBR.best_score_, grid_GBR.best_params_))

Solution

  • This works for me

    pip install keras==2.12.0
    

    Another Approach you can try

    pip uninstall tensorflow
    pip install tensorflow==2.12.0