在keras分类器中计算w.r.t类的梯度

时间:2020-02-07 21:41:59

标签: python tensorflow keras deep-learning tf.keras

我正在努力在keras(tf后端)的ANN分类器的输出层中计算w.r.t类的梯度。 这是模型的架构:

model = Sequential([
  Dense(64, activation='relu', input_shape=(784,)),
  Dense(64, activation='relu'),
  Dense(10, activation='softmax'),
])

这是我计算梯度的方法:

outputTensor = model.output
listOfVariableTensors = model.trainable_weights[4]
gradients = k.gradients(outputTensor, listOfVariableTensors)
evaluated_gradients[0].shape

我获得了(784,10)的形状(64,10)。我认为问题出在可变张量列表中。

2 个答案:

答案 0 :(得分:0)

如果要获取相对于输入的输出梯度,则实际上是雅可比,梯度是为标量函数定义的,因此您需要执行以下操作:

from tensorflow.python.ops.parallel_for.gradients import jacobian
gradients = jacobian(model.output, model.input)

它的形状应为(samples, 784, None, 10)

答案 1 :(得分:0)

我找到了解决方法


def jacobian_tensorflow(x,M=10):    
    jacobian_matrix = []
    for m in range(M):
        # We iterate over the M elements of the output vector
        grad_func = tf.gradients(model.output[:, m], model.input)
        gradients = sess.run(grad_func, feed_dict={model.input: x.reshape((1, x.size))})
        jacobian_matrix.append(gradients[0][0,:])

    return np.array(jacobian_matrix)

谢谢大家