使用Keras获得相对于输入的损失函数梯度的错误

时间:2018-11-10 02:20:43

标签: python tensorflow keras

model = keras.Sequential([         #my model, trained on Fashion_MNIST
    keras.layers.Conv2D(32, (3,3), activation=tf.nn.relu, input_shape=(28,28,1)),
    keras.layers.MaxPooling2D(),
    keras.layers.Conv2D(64, (3,3), activation=tf.nn.relu),
    keras.layers.MaxPooling2D(),
    keras.layers.Flatten(),
    keras.layers.Dense(1000, activation='relu'),
    keras.layers.Dense(10, activation=tf.nn.softmax)
])

model.load_weights('./weights/235model')            #load weights
model.compile(optimizer=tf.train.AdamOptimizer(),   
          loss='sparse_categorical_crossentropy',
          metrics=['accuracy'])

tmp = np.full((10,1),0.0)                           #get correct label
tmp[test_labels[0]] = 1.0
y_tensor=tf.convert_to_tensor(tmp)

loss = keras.losses.sparse_categorical_crossentropy(model.output,    y_tensor)
gradients = keras.backend.gradients(loss, model.input)
print(gradients)

我正在进行迭代FGSM攻击,因此我需要获得相对于输入的损耗梯度,但是当我打印梯度时,它显示 [无]代替有效张量。

后来我运行它,

with keras.backend.get_session() as sess:

    evaluated_gradients = sess.run(gradients, feed_dict={model.input:np.reshape(test_images[0],(1,28,28,1))})

这给我错误 /.local/lib/python2.7/site-packages/tensorflow/python/client/session.py“,第258行,在for_fetch中     类型(获取)) TypeError:获取参数None的类型无效

如果我在设置渐变时将损失更改为model.output,它可以正常工作,但是如果我在此处使用交叉熵损失,则它不起作用,有人可以帮助我吗?我是keras和tensorflow的初学者。

1 个答案:

答案 0 :(得分:0)

您将参数的顺序翻转为keras.losses.sparse_categorical_crossentropy。应该是

loss = keras.losses.sparse_categorical_crossentropy(y_tensor, model.output)

https://keras.io/losses/#sparse_categorical_crossentropy