python-3.x - 在 Tensorflow 中计算雅可比和导数非常慢
问题描述
是否有一种更有效的方法来计算雅可比行列式(必须有,它甚至不会针对单个批次运行)我想计算自解释神经网络中给出的损失。输入的形状为 (32, 365, 3),其中 32 是批量大小。我想最小化的损失是论文的公式 3 。
我相信我没有以最佳方式使用 GradientTape。
def compute_loss_theta(tape, parameter, concept, output, x):
b = x.shape[0]
in_dim = (x.shape[1], x.shape[2])
feature_dim = in_dim[0]*in_dim[1]
J = tape.batch_jacobian(concept, x)
grad_fx = tape.gradient(output, x)
grad_fx = tf.reshape(grad_fx,shape=(b, feature_dim))
J = tf.reshape(J, shape=(b, feature_dim, feature_dim))
parameter = tf.expand_dims(parameter, axis =1)
loss_theta_matrix = grad_fx - tf.matmul(parameter, J)
loss_theta = tf.norm(loss_theta_matrix)
return loss_theta
for i in range(10):
for x, y in train_dataset:
with tf.GradientTape(persistent=True) as tape:
tape.watch(x)
parameter, concept, output = model(x)
loss_theta = compute_loss_theta(tape, parameter, concept, output , x)
loss_y = loss_object(y_true=y, y_pred=output)
loss_value = loss_y + eps*loss_theta
gradients = tape.gradient(loss_value, model.trainable_weights)
optimizer.apply_gradients(zip(gradients, model.trainable_weights))
解决方案
推荐阅读
- c# - 我可以从 C# .Net 驱动程序中多个文档中存在的数组中提取多个元素吗
- python - 根据原始列表中的数字重复的列表
- flutter - 如何根据 Flutter 中的项目更改底部表的高度?
- java - Mapstruct - 通用映射器
- python - 哈希值是如何计算的?为什么每次运行脚本时对象的哈希值都会发生变化?
- python - 从源代码构建 Papagayo(Lip Sync Tool)的问题
- mysql - EntityFramework.dll 中的 ASP.NET MVC 'System.NullReferenceException'
- linux - org.openqa.selenium.SessionNotCreatedException:会话未在 centos 终端断开连接时创建
- python - 在 Pandas 数据框中设置小数点精度
- python - scikit-image color.rgb2gray 警告