我目前正在尝试使用张量流生成一些对抗图像。我现在有一个有效的代码可以欺骗分类NN(初始v3),并且我想欺骗一个检测器。我选择Mask-RCNN。 我成功检索了日志,但是我不明白为什么会有错误:
ValueError:没有为任何变量提供渐变,请检查您的图表 对于不支持渐变的操作,请在变量之间[“ tf.Variable'Variable_33:0'shape =(299,299,3)dtype = float32_ref“] 和损失Tensor(“ softmax_cross_entropy_with_logits_9 / Reshape_2:0”, shape =(1,),dtype = float32)。
这是我的完整代码:
sess = tf.InteractiveSession()
image = tf.Variable(tf.zeros((299, 299, 3)))
x = tf.placeholder(tf.float32, (299, 299, 3))
adv = image
assign_op = tf.assign(adv, x)
learning_rate = tf.placeholder(tf.float32, ())
y_hat = tf.placeholder(tf.int32, ())
logits = tf.Variable(logits_[0])
labels = tf.one_hot(y_hat, 81)
loss = tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=[labels])
optim_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, var_list=adv)
epsilon = tf.placeholder(tf.float32, ())
projected = tf.clip_by_value(tf.clip_by_value(adv, x - epsilon, x + epsilon), 0, 1)
with tf.control_dependencies([projected]):
project_step = tf.assign(adv, projected)
demo_epsilon = 2.0/255.0 # a really small perturbation
demo_lr = 1e-1
demo_target = 2
sess.run(assign_op, feed_dict={x: images[0]})
for i in range(100):
_, loss_value = sess.run([optim_step, loss], feed_dict={learning_rate: demo_lr, y_hat: demo_target})
assign_ope = logits.assign(fast_rcnn_1(img))
sess.run(assign_ope)
sess.run(project_step, feed_dict={x: img, epsilon: demo_epsilon})
if (i+1) % 10 == 0:
print('step %d, loss=%g' % (i+1, loss_value))
adversarial = adv.eval()
然后我用:
def fast_rcnn_1(image):
molded_image, window, scale, padding, crop = resize_image(
image,
min_dim=IMAGE_MIN_DIM,
min_scale=IMAGE_MIN_SCALE,
max_dim=IMAGE_MAX_DIM,
mode=IMAGE_RESIZE_MODE)
molded_image = mold_image(molded_image)
image_meta = compose_image_meta(
0, image.shape, molded_image.shape, window, scale,
np.zeros([NUM_CLASSES], dtype=np.int32))
image_shape = molded_image.shape
anchors = model.get_anchors(image_shape)
anchors = np.broadcast_to(anchors, (1,) + anchors.shape)
logit = model2.predict([molded_image[None,...], image_meta[None,...], anchors], verbose=1)[0][0]
prob = softmax(logit)
return logit
model2是通过在“ mrcnn_class_logits”层上切割蒙版rcnn模型获得的:
model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)
model.load_weights(COCO_MODEL_PATH, by_name=True)
layer_name = 'mrcnn_class_logits'
model2= Model(inputs=model.keras_model.input, outputs=model.keras_model.get_layer(layer_name).output)
我的tensorflow版本是1.9.0。 我曾经尝试过更改logit和标签的形状,但问题似乎出自另一个错误。
答案 0 :(得分:0)
我认为错误来自此行:
model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)
这将在推理模式下为MaskRCNN创建图形,该图形通过删除一些操作来提高推理性能,将可训练的变量置于False并停止梯度传播。
只需将“模式”属性更改为训练,就可以了。