0

我正在尝试使用自动编码器进行深度傻瓜攻击,但它给了我以下错误:

InvalidArgumentError                      Traceback (most recent call
last)
c:\users\MrUserMan\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\client\session.py
in _do_call(self, fn, *args)    1333     try:
-> 1334       return fn(*args)    1335     except errors.OpError as e:

c:\users\MrUserMan\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\client\session.py
in _run_fn(feed_dict, fetch_list, target_list, options, run_metadata) 
1318       return self._call_tf_sessionrun(
-> 1319           options, feed_dict, fetch_list, target_list, run_metadata)    1320 

c:\users\MrUserMan\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\client\session.py
in _call_tf_sessionrun(self, options, feed_dict, fetch_list,
target_list, run_metadata)    1406         self._session, options,
feed_dict, fetch_list, target_list,
-> 1407         run_metadata)    1408 

InvalidArgumentError: ValueError: could not broadcast input array from
shape (28,28,28) into shape (28,28,1) Traceback (most recent call
last):

  File
"c:\users\MrUserMan\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\ops\script_ops.py",
line 206, in __call__
    ret = func(*args)

  File
"c:\users\MrUserMan\appdata\local\programs\python\python35\lib\site-packages\cleverhans\attacks\__init__.py",
line 1463, in deepfool_wrap
    self.nb_classes)

  File
"c:\users\MrUserMan\appdata\local\programs\python\python35\lib\site-packages\cleverhans\attacks_tf.py",
line 1222, in deepfool_batch
    feed=feed)

  File
"c:\users\MrUserMan\appdata\local\programs\python\python35\lib\site-packages\cleverhans\attacks_tf.py",
line 1294, in deepfool_attack
    r_tot[idx, ...] = r_tot[idx, ...] + r_i

ValueError: could not broadcast input array from shape (28,28,28) into
shape (28,28,1)


     [[{{node PyFunc}} = PyFunc[Tin=[DT_FLOAT], Tout=[DT_FLOAT],
token="pyfunc_0",
_device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_Placeholder_2_0_0)]]

During handling of the above exception, another exception occurred:

InvalidArgumentError                      Traceback (most recent call
last) <ipython-input-19-650e99de52f0> in <module>
      1 deepfool = DeepFool(model, sess=sess)
      2 
----> 3 adv_x = deepfool.generate_np(X_test, overshoot=0.02, max_iter=50, nb_candidate=2)

c:\users\MrUserMan\appdata\local\programs\python\python35\lib\site-packages\cleverhans\attacks\__init__.py
in generate_np(self, x_val, **kwargs)
    201       feed_dict[new_kwargs[name]] = feedable[name]
    202 
--> 203     return self.sess.run(x_adv, feed_dict)
    204 
    205   def construct_variables(self, kwargs):

c:\users\MrUserMan\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\client\session.py
in run(self, fetches, feed_dict, options, run_metadata)
    927     try:
    928       result = self._run(None, fetches, feed_dict, options_ptr,
--> 929                          run_metadata_ptr)
    930       if run_metadata:
    931         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

c:\users\MrUserMan\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\client\session.py
in _run(self, handle, fetches, feed_dict, options, run_metadata)   
1150     if final_fetches or final_targets or (handle and
feed_dict_tensor):    1151       results = self._do_run(handle,
final_targets, final_fetches,
-> 1152                              feed_dict_tensor, options, run_metadata)    1153     else:    1154       results = []

c:\users\MrUserMan\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\client\session.py
in _do_run(self, handle, target_list, fetch_list, feed_dict, options,
run_metadata)    1326     if handle is None:    1327       return
self._do_call(_run_fn, feeds, fetches, targets, options,
-> 1328                            run_metadata)    1329     else:    1330       return self._do_call(_prun_fn, handle, feeds, fetches)

c:\users\MrUserMan\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\client\session.py
in _do_call(self, fn, *args)    1346           pass    1347      
message = error_interpolation.interpolate(message, self._graph)
-> 1348       raise type(e)(node_def, op, message)    1349     1350   def _extend_graph(self):

InvalidArgumentError: ValueError: could not broadcast input array from
shape (28,28,28) into shape (28,28,1) Traceback (most recent call
last):

这是我的代码:

import numpy as np
from keras import backend
import tensorflow as tf
from keras.callbacks import ModelCheckpoint
from matplotlib import gridspec

from cleverhans.attacks import FastGradientMethod
from cleverhans.attacks import BasicIterativeMethod
from cleverhans.attacks import SaliencyMapMethod
from cleverhans.attacks import DeepFool

from cleverhans.utils_keras import KerasModelWrapper

from matplotlib import pyplot as plt
from sklearn.metrics import confusion_matrix, classification_report

from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils

sess =  backend.get_session()
x = tf.placeholder(tf.float32, shape=(None, 28, 28, 1))
y = tf.placeholder(tf.float32, shape=(None, 10))

(X_train, y_train), (X_test, y_test) = mnist.load_data()
x_train = X_train.astype('float32') / 255.
x_test = X_test.astype('float32') / 255.
x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))
x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))
X_train = x_train
X_test = x_test

# one hot encode outputs
y_train_cat = np_utils.to_categorical(y_train)
y_test_cat = np_utils.to_categorical(y_test)
num_classes = y_test_cat.shape[1]

input_img = Input(shape=(784,)) # 784

encoded = Dense(784, activation='relu')(input_img)
encoded = Dense(504, activation='relu')(encoded)
encoded = Dense(140, activation='relu')(encoded)

decoded = Dense(140, activation='relu')(encoded)
decoded = Dense(504, activation='softplus')(decoded)
decoded = Dense(784, activation='sigmoid')(decoded
autoencoder = Model(input_img, decoded)
autoencoder.summary()

autoencoder.compile(optimizer='adam', loss='categorical_crossentropy')
history = autoencoder.fit(X_train, X_train, epochs=35, batch_size=1024, validation_data=(X_test, X_test), verbose=1)

decoded_imgs = (autoencoder.predict(X_train))
decoded_imgs_test = (autoencoder.predict(X_test))
decoded_int = np.round(decoded_imgs*255).astype(int)
decoded_int_test = np.round(decoded_imgs_test*255).astype(int)
X_train = decoded_int
X_test = decoded_int_test

#Making Input eligible for DeepFool
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)

model = Sequential()
model.add(Conv2D(32, (5, 5), input_shape=(28,28,1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dense(num_classes, activation='sigmoid'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.summary()
history = model.fit(X_train, y_train_cat, epochs=35, batch_size=1024, verbose=1,
                    validation_split=0.7)
deepfool = DeepFool(model, sess=sess)

adv_x = deepfool.generate_np(X_test, overshoot=0.02, max_iter=50, nb_candidate=2)
4

1 回答 1

0

失败的原因是您正在运行的某些代码试图将大小数组重塑为大小(28, 28, 28)(28, 28)因此数组中的元素数量不一样。

在传递给 DeepFool 攻击对象之前,您是否使用 KerasModelWrapper 包装了您的模型?

于 2019-06-17T13:57:36.537 回答