pythonmachine-learningkerasattributeerror

.predict() in Python gives an Attribute Error


def train_model(x_train, y_train, dropout_prob, lr, batch_size, epochs):
    nn_model = tf.keras.Sequential([
        tf.keras.layers.Dense(64, activation='relu', input_shape=(10,)),
        tf.keras.layers.Dropout(dropout_prob),
        tf.keras.layers.Dense(32, activation='relu'),
        tf.keras.layers.Dropout(dropout_prob),
        tf.keras.layers.Dense(1, activation='sigmoid')
        ])

    nn_model.compile(keras.optimizers.Adam(lr), loss='binary_crossentropy', metrics=['accuracy'])

    history = nn_model.fit(
        x_train,y_train,epochs=epochs, batch_size=batch_size, validation_split=0.2, verbose=0
    )

    plot_history(history)

    return nn_model, history


least_loss_model = train_model(x_train, y_train, 0.2, 0.005, 128, 100)
predicted = least_loss_model.predict(x_test)
print(predicted)

This is giving the following attribute error:

Traceback (most recent call last):
  File "C:\Users\~\ai.py", line 162, in <module>
    predicted = least_loss_model.predict(x_test)
                ^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'tuple' object has no attribute 'predict'

I have already tried predicted = least_loss_model.predict_proba(x_test).


Solution

  • This is because you are returning a history and nn_model, which would return a type tuple. if you just return nn_model and then do the same it would work. Else try this:

    predicted = least_loss_model[0].predict(x_test)
    

    This should work.