3
假設我有一個簡單的一層神經網絡:SOFTMAX雅可比在Tensorflow
x = tf.placeholder(tf.float32, [batch_size, input_dim])
W = tf.Variable(tf.random_normal([input_dim, output_dim]))
a = tf.matmul(x, W)
y = tf.nn.softmax(a)
因此,可變y
通過output_dim
是尺寸batch_size
的。我想針對批次中的每個樣本計算y
的雅可比,其相對於a
,其尺寸爲batch_size
,output_dim
,output_dim
。現在,在數學上,對於i!= j和另外的(dy/da)_ {i,i} = y_i(1-y_i),Jacobian(dy/da)_ {i,j} = - y_i y_j。
我想知道如何計算softmax相對於其在TensorFlow中的輸入的雅可比行列式?我知道tf.gradients
將計算標量關於張量的梯度,所以我將TensorFlow中的循環與tf.gradients
中的一些循環結合起來,甚至只是試圖實現上面給出的分析形式應該可行。但我不確定如何在TensorFlow中使用它的操作來做到這一點,並會欣賞任何代碼來做到這一點!