Home > OS >  AttributeError: 'KerasRegressor' object has no attribute '__call__'
AttributeError: 'KerasRegressor' object has no attribute '__call__'

Time:08-31

I am building artificial neuron network (ANN) model for predicting values but facing problem:

Input:

def create_model(optimizer = 'rmsprop', units = 16, learning_rate = 0.001):
    ann = Sequential() # Initialising ANN
    ann.add(tf.keras.layers.Dense(units = units, activation = "relu")) # Adding First Hidden Layer
    ann.add(tf.keras.layers.Dense(units = units, activation = "relu")) # Adding Second Hidden Layer
    ann.add(tf.keras.layers.Dense(units = units, activation = "relu")) # Adding Third Hidden Layer
    ann.add(tf.keras.layers.Dense(units = 1)) # Adding Output Layer   
    ann.compile(optimizer = optimizer, loss = 'mean_absolute_error') # Compiling ANN
    return ann

ann = KerasRegressor(model = create_model, 
                     verbose = 0, 
                     learning_rate = 0.001, 
                     units = 16
                     )
 
optimizers = ['rmsprop', 'adam', 'SGD']
epoch_values = [10, 25, 50, 100, 150, 200]
batches = [10, 20, 30, 40, 50, 100, 1000]
units = [16, 32, 64, 128, 256]
lr_values = [0.001, 0.01, 0.1, 0.2, 0.3]

hyperparameters = dict(optimizer = optimizers, 
                        epochs = epoch_values, 
                        batch_size = batches, 
                        units = units,
                        learning_rate = lr_values
                        )

grid = GridSearchCV(estimator = ann, cv = 5, param_grid = hyperparameters)

history = grid.fit(X_train, 
                   Y_train, 
                   batch_size = 32, 
                   validation_data = (X_test, Y_test), 
                   epochs = 100
                   ) # Fitting ANN

Output error:

...
92 elif (not isinstance(self.build_fn, types.FunctionType) and
93       not isinstance(self.build_fn, types.MethodType)):
94   legal_params_fns.append(self.build_fn.__call__)

AttributeError: 'KerasRegressor' object has no attribute '__call__'

Data:

  • X.shape -> (10, 2066)
  • Y.shape -> (10, 4)
  • X_train.shape -> (8, 2066)
  • X_test.shape -> (2, 2066)
  • Y_train.shape -> (8, 4)
  • Y_test.shape -> (2, 4)

CodePudding user response:

You have to compile the model before passing it to KerasRegressor:

...
model = create_model()
model.compile()
ann = KerasRegressor(model)
...
  • Related