Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error:'_UserObject' object has no attribute 'predict'

Tags:

python

I am building an ANN model for machine learning against a data train. when I call the model to validate the test data, an error occurs

model = Sequential()
model.add(Dense(8,activation='tanh',input_dim = 10))

model.add(Dense(6,activation='tanh'))

model.add(Dense(4,activation='softmax'))

model.summary()

from tensorflow.keras.models import Sequential, save_model, load_model

filepath = './input/saved_model'

save_model(model, filepath)

test = pd.read_csv('test.csv')

enter code here

when I process the code below, an error message appears

predictions = model.predict(test)

AttributeError                            Traceback (most recent call last)

<ipython-input-141-82c4f2e9fa53> in <module>()

----> 1 predictions = model.predict(test)

AttributeError: '_UserObject' object has no attribute 'predict'
like image 283
M. Rangga Ramadhan Saelan MGG Avatar asked Apr 02 '26 11:04

M. Rangga Ramadhan Saelan MGG


2 Answers

You have saved your model using .save_model method of the tensorflow.keras.models. This by default saves it in SavedModel format of tensorflow.

When you load back the model using tensorflow.keras.models.load_model method, you can use the predict method of the model.

model = tf.keras.models.load_model(<saved_model_folder>)
predictions = model.predict(input_tensor)

But if you try to load the same model, which was saved using the tf.keras.models.save_model, using tf.saved_model.load you have to do it in this way:

model = tf.saved_model.load(<saved_model_folder>)
predictions = model(input_tensor) # Notice predict is not used.

The is written in the Note section of https://www.tensorflow.org/api_docs/python/tf/keras/Model#call.

If you want inference(predict) function, you can do it as follows:

model_loaded = tf.keras.models.load_model(<saved_model_folder>)
DEFAULT_FUNCTION_KEY = 'serving_default'
predict_func = model_loaded.signatures[DEFAULT_FUNCTION_KEY]

for batch in predict_dataset.take(1):
    print(predict_func(batch))

I think you are using keras API to save and saved_model API to load the model and hence the issue.

like image 119
MSS Avatar answered Apr 09 '26 18:04

MSS


I solved this issue by using the older keras h5 format: h5-format

Simply load and save the model with the .h5 extension:

model.save('model_name.h5')
loaded_model = keras.model.load_model('model_name.h5')
like image 36
simple_42 Avatar answered Apr 09 '26 18:04

simple_42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!