【发布时间】:2015-08-10 12:39:20
【问题描述】:
在我的代码中,我使用 theano 来计算欧几里得距离矩阵(代码来自 here):
import theano
import theano.tensor as T
MAT = T.fmatrix('MAT')
squared_euclidean_distances = (MAT ** 2).sum(1).reshape((MAT.shape[0], 1)) + (MAT ** 2).sum(1).reshape((1, MAT.shape[0])) - 2 * MAT.dot(MAT.T)
f_euclidean = theano.function([MAT], T.sqrt(squared_euclidean_distances))
def pdist_euclidean(mat):
return f_euclidean(mat)
但是下面的代码导致矩阵的一些值是NaN。我读到在计算theano.tensor.sqrt() 和here 时会发生这种情况,建议
在 sqrt(或 max(x,EPs))内添加一个 eps
所以我在我的代码中添加了一个 eps:
import theano
import theano.tensor as T
eps = 1e-9
MAT = T.fmatrix('MAT')
squared_euclidean_distances = (MAT ** 2).sum(1).reshape((MAT.shape[0], 1)) + (MAT ** 2).sum(1).reshape((1, MAT.shape[0])) - 2 * MAT.dot(MAT.T)
f_euclidean = theano.function([MAT], T.sqrt(eps+squared_euclidean_distances))
def pdist_euclidean(mat):
return f_euclidean(mat)
我在执行sqrt 之前添加它。我得到的NaNs 越来越少,但我仍然得到它们。问题的正确解决方案是什么?我还注意到,如果 MAT 是 T.dmatrix() 则没有 NaN
【问题讨论】:
-
添加负值检查并打印数据,以便追踪它们的来源。
-
@stark 我在
squared_euclidean_distances中有负值,我应该使用T.abs_吗? -
没有。你应该找出你的函数出了什么问题。
-
@stark 应该没问题,我是从stackoverflow.com/questions/25886374/pdist-for-theano-tensor 拿的,用
dmatrix代替fmatrix没有NaN -
abs 仍然没有意义。如果为负数,只需使用 0.0。