Почему я получаю AttributeError: модуль «tensorflow.keras.backend» не имеет атрибута «placeholder» при использовании KerPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Почему я получаю AttributeError: модуль «tensorflow.keras.backend» не имеет атрибута «placeholder» при использовании Ker

Сообщение Anonymous »

Я пытаюсь использовать Adversarial Robustness Toolbox (ART) с простой моделью Keras в TensorFlow 2.x, но сталкиваюсь со следующей ошибкой:

Код: Выделить всё

AttributeError: module 'tensorflow.keras.backend' has no attribute 'placeholder
Мой код выглядит так:

Код: Выделить всё

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[i].reshape(28, 28), cmap="gray")
plt.title("Original")
plt.axis("off")

plt.subplot(2, 5, i + 6)
plt.imshow(x_test_adv[i].reshape(28, 28), cmap="gray")
plt.title("Adversarial")
plt.axis("off")
plt.tight_layout()
plt.show()
Эта ошибка возникает в библиотеке ART при инициализации KerasClassifier. У меня установлен TensorFlow 2.x, и я использую последнюю версию Adversarial Robustness Toolbox (ART).
Что я пробовал:
  • Отключение быстрого выполнения с помощью tf.compat.v1.disable_eager_execution(), но это не решает проблему.
  • Проверка наличия обновлений для АРТ или TensorFlow, но все актуально.
Может ли кто-нибудь подсказать, почему возникает эта ошибка и как ее устранить в TensorFlow 2.x?< /п>

Подробнее здесь: https://stackoverflow.com/questions/793 ... -attribute
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»