【发布时间】:2021-10-07 09:44:12
【问题描述】:
我正在使用 tf.GradientTape().gradient() 来计算 representer point,它可用于计算给定训练示例对给定测试示例的“影响”。给定测试示例x_t 和训练示例x_i 的表示点计算为它们的特征表示f_t 和f_i 乘以权重alpha_i 的点积。
注意:此方法的详细信息对于理解问题不是必需的,因为主要问题是让渐变胶带起作用。话虽如此,我已经为任何感兴趣的人提供了以下一些详细信息的屏幕截图。
计算 alpha_i 需要微分,因为它表示如下:
在上面的等式中,L 是标准损失函数(多类分类的分类交叉熵),phi 是 pre-softmax 激活输出(所以它的长度是类的数量)。此外,alpha_i 可以进一步分解为alpha_ij,它是针对特定类j 计算的。因此,我们只需得到测试样例的预测类别(最终预测最高的类别)对应的pre-softmax输出phi_j。
我使用 MNIST 创建了一个简单的设置并实现了以下功能:
def simple_mnist_cnn(input_shape = (28,28,1)):
input = Input(shape=input_shape)
x = layers.Conv2D(32, kernel_size=(3, 3), activation="relu")(input)
x = layers.MaxPooling2D(pool_size=(2, 2))(x)
x = layers.Conv2D(64, kernel_size=(3, 3), activation="relu")(x)
x = layers.MaxPooling2D(pool_size=(2, 2))(x)
x = layers.Flatten()(x) # feature representation
output = layers.Dense(num_classes, activation=None)(x) # presoftmax activation output
activation = layers.Activation(activation='softmax')(output) # final output with activation
model = tf.keras.Model(input, [x, output, activation], name="mnist_model")
return model
现在假设模型已经过训练,我想计算给定训练示例对给定测试示例的预测的影响,可能是出于模型理解/调试目的。
with tf.GradientTape() as t1:
f_t, _, pred_t = model(x_t) # get features for misclassified example
f_i, presoftmax_i, pred_i = model(x_i)
# compute dot product of feature representations for x_t and x_i
dotps = tf.reduce_sum(
tf.multiply(f_t, f_i))
# get presoftmax output corresponding to highest predicted class of x_t
phi_ij = presoftmax_i[:,np.argmax(pred_t)]
# y_i is actual label for x_i
cl_loss_i = tf.keras.losses.categorical_crossentropy(pred_i, y_i)
alpha_ij = t1.gradient(cl_loss_i, phi_ij)
# note: alpha_ij returns None currently
k_ij = tf.reduce_sum(tf.multiply(alpha_i, dotps))
上面的代码给出了以下错误,因为 alpha_ij 为无:ValueError: Attempt to convert a value (None) with an unsupported type (<class 'NoneType'>) to a Tensor.。但是,如果我更改 t1.gradient(cl_loss_i, phi_ij) -> t1.gradient(cl_loss_i, presoftmax_i),它将不再返回 None。不知道为什么会这样?在切片张量上计算梯度是否存在问题? “观察”太多变量是否存在问题?我对渐变胶带的工作不多,所以我不确定修复方法是什么,但希望能得到帮助。
【问题讨论】:
-
为什么在张量流梯度中使用 numpy?这几乎肯定是问题所在。
-
不知道有没有问题?例如,在某些情况下,tensorflow 文档在梯度磁带内使用 numpy 操作:tensorflow.org/guide/autodiff。但可以肯定的是,我将
np.argmax(pred_t)切换为固定索引(例如0),问题仍然存在。
标签: tensorflow neural-network slice tensorflow2.0 automatic-differentiation