我在 Keras/Tensrflow 中找到了 Earth Mover Loss 的代码。我想计算图像得分的损失,但在了解下面给出的推土机损失的工作原理之前我无法做到这一点。有人可以描述一下代码中发生的情况吗?
模型的最后一层或输出层如下:
out = Dense(10,activation='softmax')(x)
Run Code Online (Sandbox Code Playgroud)
这个方法的输入类型应该是什么。我有等y_labels的形式1.2,4.9。我想将它与 Keras/Tensorflow 一起使用
def earth_mover_loss(y_true, y_pred):
cdf_true = K.cumsum(y_true, axis=-1)
cdf_pred = K.cumsum(y_pred, axis=-1)
emd = K.sqrt(K.mean(K.square(cdf_true - cdf_pred), axis=-1))
return K.mean(emd)
Run Code Online (Sandbox Code Playgroud) 在我的代码中,我使用theano来计算欧氏距离矩阵(此处的代码):
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)
Run Code Online (Sandbox Code Playgroud)
但是下面的代码会导致矩阵的某些值NaN.我已经读过,计算时会发生这种情况,theano.tensor.sqrt()并建议在这里进行
在sqrt中添加eps(或max(x,EP))
所以我在代码中添加了一个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)
Run Code Online (Sandbox Code Playgroud)
而且我在表演前添加它 …