FailedPreconditionError:尝试使用未初始化的密集值

时间:2018-06-07 15:03:13

标签: python tensorflow machine-learning

我正在尝试为恶意检测的对抗示例构建模型。 但是收到错误

尝试使用未初始化的值dense_24 / bias

即使我将所有变量初始化为全局变量,并记住会话。 这是完整的代码

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    tf.set_random_seed(42)
    def mlp_model ():
        model_adv = Sequential()
        model_adv.add(Dense (256, activation ='relu', input_shape =(X_train.shape[1],)))
        model_adv.add(Dropout(0.4))
        model_adv.add(Dense(256, activation ='relu'))
        model_adv.add(Dropout(0.4))
        model_adv.add(Dense(2, activation ='softmax'))
        model_adv.compile(loss ='categorical_crossentropy', optimizer ='adam', metrics = ['accuracy'])

        model_adv.summary()

        return model_adv

    model_adv = mlp_model()


    source_samples = X_test.shape[0]
    X_adv = np.empty((0,36)) #numpy.empty(shape, dtype = float, order = ‘C’) : Return a new array of given shape and type, with random values.generating empty array with shape same as X_test data
    jsma = SaliencyMapMethod(model_adv, back = 'tf', sess = sess) #initializing object for saliencyMapMethod
    jsma_params = {'theta': 1., 'gamma': 0.1, 'clip_min': 0., 'clip_max': 1., 'y_target': None}
    print (jsma)




    for sample_ind in range(0, source_samples):
        print('Generating sample no: ' + str(sample_ind))

        sample = X_test[sample_ind:(sample_ind+1)]


        current_class = int(np.argmax(y_test[sample_ind]))
        target_classes = other_classes(2, current_class)

        if current_class != 0 :
            target_classes = [0]
        else :
            rand_class = random.randint(1,1)
            target_classes = [rand_class]


        for target in target_classes:
            one_hot_target = np.zeros((1, 2), dtype=np.float32)
            one_hot_target[0, target] = 1
            jsma_params['y_target'] = one_hot_target

            adv_x = jsma.generate_np(sample, **jsma_params)


            X_adv = np.vstack([X_adv, adv_x])

    print (X_adv.shape)

错误: -

FailedPreconditionError                   Traceback (most recent call last)
~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
   1321     try:
-> 1322       return fn(*args)
   1323     except errors.OpError as e:

~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run_fn(feed_dict, fetch_list, target_list, options, run_metadata)
   1306       return self._call_tf_sessionrun(
-> 1307           options, feed_dict, fetch_list, target_list, run_metadata)
   1308 

~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _call_tf_sessionrun(self, options, feed_dict, fetch_list, target_list, run_metadata)
   1408           self._session, options, feed_dict, fetch_list, target_list,
-> 1409           run_metadata)
   1410     else:

FailedPreconditionError: Attempting to use uninitialized value dense_24/bias
 [[Node: dense_24/bias/read = Identity[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](dense_24/bias)]]

 During handling of the above exception, another exception occurred:

FailedPreconditionError                   Traceback (most recent call last)
<ipython-input-47-6bcd7b5e2de4> in <module>()
     54             jsma_params['y_target'] = one_hot_target
     55 
---> 56             adv_x = jsma.generate_np(sample, **jsma_params)
     57 
     58 

c:\users\nishant\src\cleverhans\cleverhans\attacks.py in generate_np(self, x_val, **kwargs)
    156             feed_dict[new_kwargs[name]] = feedable[name]
    157 
--> 158         return self.sess.run(x_adv, feed_dict)
    159 
    160     def construct_variables(self, kwargs):

~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
    898     try:
    899       result = self._run(None, fetches, feed_dict, options_ptr,
--> 900                          run_metadata_ptr)
    901       if run_metadata:
    902         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1133     if final_fetches or final_targets or (handle and feed_dict_tensor):
   1134       results = self._do_run(handle, final_targets, final_fetches,
-> 1135                              feed_dict_tensor, options, run_metadata)
   1136     else:
   1137       results = []

~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1314     if handle is None:
   1315       return self._do_call(_run_fn, feeds, fetches, targets, options,
-> 1316                            run_metadata)
   1317     else:
   1318       return self._do_call(_prun_fn, handle, feeds, fetches)

~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
   1333         except KeyError:
   1334           pass
-> 1335       raise type(e)(node_def, op, message)
   1336 
   1337   def _extend_graph(self):

FailedPreconditionError: Attempting to use uninitialized value dense_24/bias
 [[Node: dense_24/bias/read = Identity[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](dense_24/bias)]]

最初,我删除了缩进for循环(对于范围内的sample_ind(0,source_samples) 但它给了     会话关闭错误

我的模型有问题吗?

1 个答案:

答案 0 :(得分:0)

您似乎正在使用Keras定义模型。如果确实如此,则在对CleverHans模型进行攻击之前,必须先将Keras模型包装为CleverHans模型。您可以在以下教程中找到示例:https://github.com/tensorflow/cleverhans/blob/master/cleverhans_tutorials/mnist_tutorial_keras_tf.py