2

I am using Sci-kit learn's pipeline with a KerasClassfier at the end. The classifier would load in the trained model for prediction. But after adding the classifier to the pipeline (3 components in total), I received an error AttributeError: 'KerasClassifier' object has no attribute 'model' after calling pipeline.predict_proba. I think it expects me to fit it but I am importing a trained model. I can't find anything relevant online. Your kind help is greatly appreciated. The following is relevant part of my code:

def buildEngModelByLoading():
  # load json and create model
  json_file = open('saved_model/cnnModel.json', 'r')
  loaded_model_json = json_file.read()
  json_file.close()
  loaded_model = model_from_json(loaded_model_json)
  # load weights into new model
  loaded_model.load_weights("saved_model/cnnModel.h5")
  print("Loaded classifier model")
  return loaded_model

engSklearnCnn = KerasClassifier(build_fn=buildEngModelByLoading, epochs=20, batch_size=batchSize, verbose=1)
#Append classfier to one pipeline
pipeline.steps.insert(2,['classifier',engSklearnCnn])`

1 Answer 1

1

That's because you forgot to use compile method first before predict function.

buildEngModelByLoading().compile(optimizer = 'classifier_optimizer', loss = 'loss_function', metrics = 'metrics')

Then just replace classifier_optimizer, loss_function, metrics with your parameters used.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the help. I tried your suggestion and the error says KerasClassifier has no attribute compile. I guess the wrapper makes it no longer the native Keras model. So I tried calling compile within the build function on loaded_model after loading the weights, then it gives the same error of not having attribute 'model'
@soulless, I updated my answer.You should use compile method for the imported model
Do u mean I should have it like this? Doesn't seem to to work engSklearnCnn = KerasClassifier(build_fn=buildEngModelByLoading().compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']), epochs=20, batch_size=batchSize, verbose=1)
I am supposed to call predict with pipeline.predict_proba after wrapping the keras model with the KerasClassifier wrapper
Yes, you have to use compile method before creating kerasclassifier
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.