我正在尝试编写一个自定义损失函数,如下所示:
# Compute the mahalanobis distance
def maha(x,u,S):
x_minus_u_transpose = tf.transpose(x - u)
inv_S = tf.linalg.inv(S)
x_minus_u = x - u
left_term = tf.matmul(x_minus_u, inv_S)
D_square = tf.matmul(left_term, x_minus_u_transpose)
return D_square
# Form a matrix from the prediction and compute the mahalanobis distance as loss
def custom_loss_function(vhmx,vhmy,glx,gly,l10,l11):
z = tf.zeros([32,1])
def loss(y_true,y_pred):
# 32 is the batch size
mDistance = 0
for i in range(32):
u = tf.Variable([glx,gly],validate_shape=False,dtype = tf.float32)
x = tf.Variable([vhmx,vhmy],validate_shape=False,dtype = tf.float32)
predLowerTriangularMatrix = tf.Variable([[y_pred[i],z[i]],[l10[i],l11[i]]],tf.float32)
predMatrix = tf.reshape(predLowerTriangularMatrix,[2,2])
predCovarianceMatrix = tf.matmul(predMatrix,tf.transpose(predMatrix))
mDistance = mDistance + maha(x,u,predCovarianceMatrix)
return ((1-mDistance)*(1-mDistance))/32
return loss
当我尝试拟合模型时,出现此错误。
发生异常:ValueError
变量具有None
用于渐变。请确保您所有的操作都定义了渐变(即可区分)。没有渐变的常见操作:K.argmax,K.round,K.eval。
有人可以帮我调试一下吗?