Tag Archives: #Deep learning

[Solved] Python Keras Error: AttributeError: ‘Sequential‘ object has no attribute ‘predict_classes‘

This article is about using Keras in Python to execute yhat_classes = model.predict_classes(X_test) code with an error: AttributeError: ‘Sequential’ object has no attribute ‘predict_classes’ solution.

model = Sequential()
model.add(Dense(24, input_dim=13, activation='relu'))
model.add(Dense(18, activation='relu'))
model.add(Dense(6, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
-
history = model.fit(X_train, y_train, batch_size = 256, epochs = 10, verbose = 2, validation_split = 0.2)
-
score, acc = model.evaluate(X_test, y_test,verbose=2, batch_size= 256)
print('test accuracy:', acc)
-
yhat_classes = model.predict_classes(X_test)

Cause of problem:

This predict was removed in tensorflow version 2.6_ Classes function.

Reference documents: https://keras.rstudio.com/reference/predict_proba.html#details

The following codes can be used:

predict_x=model.predict(X_test) 
classes_x=np.argmax(predict_x,axis=1)

Or

You can also try tensorflow 2.5 or other versions to solve this problem.

Using tensorflow version 2.5, there may be the following warning messages:

tensorflow\python\keras\engine\sequential.py:455: UserWarning: model.predict_classes() is deprecated and will be removed after 2021-01-01. Please use instead:* np.argmax(model.predict(x), axis=-1), if your model does multi-class classification (e.g. if it uses a softmax last-layer activation).* (model.predict(x) > 0.5).astype("int32"), if your model does binary classification (e.g. if it uses a sigmoid last-layer activation).