TypeError:仅当启用急切执行时,Tensor对象才是可迭代的。要遍历此张量,请使用tf.map_fn

时间:2019-09-13 12:06:24

标签: python tensorflow python-3.6 gradient loss

我要运行此code。 有错误的代码部分是:

   if defense_type:
         if 'gan' in defense_type:
              # Load cached dataset reconstructions.
              ...

         if FLAGS.debug:
             train_images_bb = train_images_bb[:20 * batch_size]
             train_labels_bb = train_labels_bb[:20 * batch_size]

         #Prepare the black_box model.
         prep_bbox_out = prep_bbox(
         sess, images_tensor, labels_tensor, train_images_bb,
         train_labels_bb, test_images_bb, test_labels_bb, nb_epochs,
         batch_size, learning_rate, rng=rng, gan=cur_gan,
         adv_training=adv_training,
         cnn_arch=bb_model)
   else:
         prep_bbox_out = prep_bbox(sess, images_tensor, labels_tensor,
                              train_images_bb, train_labels_bb,
                              test_images_bb, test_labels_bb,
                              nb_epochs, batch_size, learning_rate,
                              rng=rng, gan=cur_gan,
                              adv_training=adv_training,
                              cnn_arch=bb_model)

   model, bbox_preds, accuracies['bbox'] = prep_bbox_out

   # Train substitute method
   print("Training the substitute model.")
   reconstructed_tensors = tf.stop_gradient(
           gan.reconstruct(images_tensor, batch_size=batch_size,
                    reconstructor_id=1))
   model_sub, preds_sub = train_sub(
        sess, images_tensor, labels_tensor,
        model(reconstructed_tensors), images_sub,
        labels_sub,
        nb_classes, nb_epochs_s, batch_size,
        learning_rate, data_aug, lmbda, rng=rng,
        substitute_model=sub_model,
      )

但是我收到此错误:

      File "blackbox.py", line 770, in <lambda>
          main_cfg = lambda x: main(cfg, x)
      File "blackbox.py", line 686, in main
         defense_type=FLAGS.defense_type)
      File "blackbox.py", line 512, in blackbox
         reconstructor_id=1)))
      File "/usr/local/lib/python3.6/dist- 
         packages/tensorflow/python/framework/ops.py", line 477, in 
        __iter__
     "Tensor objects are only iterable when eager execution is "
 TypeError: Tensor objects are only iterable when eager execution is 
  enabled. To iterate over this tensor use tf.map_fn.  

here中的原始代码是使用python 2.7实现的,但我将其转换为python 3.6。 我使用python 3.6(google colab) Tensorslow 1.14.0,我还检查了tf 1.12.0和tf 1.8.0。

请帮我解决这个问题?如何重新编写代码以迭代张量?

0 个答案:

没有答案