the*_*ter 8 python gradient python-3.x deep-learning tensorflow
我正在将 python 3 与 anaconda 一起使用,并将 tensorflow 1.12 与eager eval 一起使用。
我正在使用它为孪生网络创建三元组损失函数,并且需要计算不同数据样本之间的距离。
我创建了一个函数来创建距离计算,但是无论我做什么,当我尝试计算它相对于网络输出的梯度时,它一直给我所有的 nan 梯度。
这是代码:
def matrix_row_wise_norm(matrix):
import tensorflow as tf
tensor = tf.expand_dims(matrix, -1)
tensor = tf.transpose(tensor, [0, 2, 1]) - tf.transpose(tensor, [2, 0, 1])
norm = tf.norm(tensor, axis=2)
return norm
Run Code Online (Sandbox Code Playgroud)
在我使用的损失函数中
def loss(y_true, p_pred):
with tf.GradientTape() as t:
t.watch(y_pred)
distance_matrix = matrix_row_wise_norm(y_pred)
grad = t.gradient(distance_matrix, y_pred)
Run Code Online (Sandbox Code Playgroud)
并且 grad 都是nan
s。我检查过它y_pred
是由合法值组成的 - 确实如此。我试图创建一个y_pred * 2
相对于自身的梯度并获得合法的梯度值。
我在这里缺少什么?创建距离矩阵时的索引是否有问题?
编辑:
两者的D型y_pred
和loss
IStf.float32
编辑:在 tf 中发现了一个打开的错误报告- 这可能是问题吗?
编辑:
当我将范数轴更改为 0 或 1 时,我得到了合法的值,而nan
. 我使用 norm with 的操作axis=2
是矩阵中行对之间的成对距离,我怀疑这可能与行与自身之间的距离为 0 有关,所以我用最小值 1e-7 剪裁了这些值没有任何运气。
谢谢
似乎 tf.norm 受到数值不稳定的影响,如此处所述
他们还建议使用数值更稳定的 l2 范数,所以我尝试了这一点,由于 0 梯度,也得到了 nan 值。所以我将它们与梯度裁剪一起使用,到目前为止一切顺利,损失函数正在工作并设法收敛。
def last_attempt(y_true, y_pred):
import tensorflow as tf
import numpy as np
loss = tf.zeros(1)
for i in range(y_pred.shape[0]):
dist = tf.gather(y_pred, [i], axis=0)
y = y_true.numpy().squeeze()
norm = tf.map_fn(tf.nn.l2_loss, dist-y_pred)
d = norm.numpy()
d[np.where(y != y[i])] = 0.0
max_pos = tf.gather(norm, np.argmax(d))
d = norm.numpy()
d[np.where(y == y[i])] = np.inf
min_neg = tf.gather(norm, np.argmin(d))
loss += tf.clip_by_value(max_pos - min_neg + tf.constant(1, dtype=tf.float32),
1e-8, 1e1)
return loss
Run Code Online (Sandbox Code Playgroud)
该功能还有很大的优化空间,这里参考了我的另一个SO 问题- 正在研究这个问题。
归档时间: |
|
查看次数: |
4831 次 |
最近记录: |