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?< /п>
Я пытаюсь использовать Adversarial Robustness Toolbox (ART) с простой моделью Keras в TensorFlow 2.x, но сталкиваюсь со следующей ошибкой: [code]AttributeError: module 'tensorflow.keras.backend' has no attribute 'placeholder[/code] Мой код выглядит так: [code]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
# 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)
# 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() [/code] Эта ошибка возникает в библиотеке ART при инициализации KerasClassifier. У меня установлен TensorFlow 2.x, и я использую последнюю версию Adversarial Robustness Toolbox (ART). Что я пробовал: [list] [*]Отключение быстрого выполнения с помощью tf.compat.v1.disable_eager_execution(), но это не решает проблему. [*]Проверка наличия обновлений для АРТ или TensorFlow, но все актуально. [/list] Может ли кто-нибудь подсказать, почему возникает эта ошибка и как ее устранить в TensorFlow 2.x?< /п>
Я пытаюсь использовать набор инструментов для устойчивости (ART) с простой моделью кераса в Tensorflow 2.x, но я сталкиваюсь с следующей ошибкой:
AttributeError: module 'tensorflow.keras.backend' has no attribute 'placeholder
Мой код выглядит...
У меня есть ошибка AttributeError: модуль «tensorflow_core.python.keras.api._v2.keras.losses» не имеет ошибки атрибута «softmax_cross_entropy» при использовании tf.losses.softmax_cross_entropy. Может ли кто-нибудь мне помочь?
import pandas as pd
import pathlib
import random
import string
import re
import numpy as np
import tensorflow as tf
import keras
from keras import layers