[Python] Why do I get AttributeError: module 'tensorflow.keras.backend' has no attribute...

Discussão em 'Python' iniciado por Stack, Junho 30, 2025.

  1. Stack

    Stack Membro Participativo

    I’m trying to use the Adversarial Robustness Toolbox (ART) with a simple Keras model in TensorFlow 2.x, but I’m encountering the following error: AttributeError: module 'tensorflow.keras.backend' has no attribute 'placeholder

    My code looks like this:

    import tensorflow as tf
    print(tf.__version__)

    import numpy as np
    from art.estimators.classification import KerasClassifier
    from art.attacks.evasion import FastGradientMethod
    from art.utils import load_mnist
    from tensorflow.keras.models import Sequential
    from tensorflow.keras.layers import Dense, Flatten
    from tensorflow.keras.optimizers import Adam

    # Load the MNIST-Dataset
    (x_train, y_train), (x_test, y_test), min_, max_ = load_mnist()
    x_train = x_train.reshape((x_train.shape[0], 28, 28, 1)).astype('float32') / 255.0
    x_test = x_test.reshape((x_test.shape[0], 28, 28, 1)).astype('float32') / 255.0

    # Create keras model
    model = Sequential([
    Flatten(input_shape=(28, 28, 1)),
    Dense(128, activation='relu'),
    Dense(10, activation='softmax')
    ])
    model.compile(optimizer=Adam(), loss='categorical_crossentropy', metrics=['accuracy'])

    # Train the model
    model.fit(x_train, y_train, epochs=3, batch_size=128, verbose=1)

    tf.compat.v1.disable_eager_execution()
    # Compile the keras modell into an ART classifiert
    classifier = KerasClassifier(model=model, clip_values=(0, 1), use_logits=False)

    # configure FGSM-attack
    attack = FastGradientMethod(estimator=classifier, eps=0.2)

    # create adversarial samples
    x_test_adv = attack.generate(x=x_test)

    # Evaluation of the model with adversarial samples
    predictions = np.argmax(classifier.predict(x_test_adv), axis=1)
    accuracy = np.sum(predictions == np.argmax(y_test, axis=1)) / len(y_test)
    print(f"Genauigkeit nach Angriff: {accuracy * 100:.2f}%")

    # Visualisation
    import matplotlib.pyplot as plt

    plt.figure(figsize=(10, 5))
    for i in range(5):
    plt.subplot(2, 5, i + 1)
    plt.imshow(x_test.reshape(28, 28), cmap="gray")
    plt.title("Original")
    plt.axis("off")

    plt.subplot(2, 5, i + 6)
    plt.imshow(x_test_adv.reshape(28, 28), cmap="gray")
    plt.title("Adversarial")
    plt.axis("off")
    plt.tight_layout()
    plt.show()


    This error is raised within the ART library when initializing the KerasClassifier. I have TensorFlow 2.x installed, and I’m using the latest version of the Adversarial Robustness Toolbox (ART).

    Things I’ve tried:

    • Disabling eager execution using tf.compat.v1.disable_eager_execution(), but it doesn't solve the issue.
    • Checking if there are any updates for ART or TensorFlow, but everything is up-to-date.

    Can anyone suggest why this error occurs and how to resolve it in TensorFlow 2.x?

    Continue reading...

Compartilhe esta Página