我想创建我的自定义损失函数。首先,模型的输出形状是(None,7,3)。所以我想将输出拆分为3个列表。但我得到如下错误:
OperatorNotAllowedInGraphError: iterating over `tf.Tensor` is not allowed: AutoGraph did convert this function. This might indicate you are trying to use an unsupported feature.
我认为不支持upper_b_true = [m[0] for m in y_true]
。我不知道如何解决这个问题。
class new_loss(tf.keras.losses.Loss):
def __init__(self, tr1, tr2):
super(new_loss, self).__init__()
self.tr1 = tr1
self.tr2 = tr2
def call(self, y_true, y_pred):
#pre-determined value
tr1 = tf.constant(self.tr1)
tr2 = tf.constant(self.tr2)
#sep
upper_b_true = [m[0] for m in y_true]
y_med_true = [m[1] for m in y_true]
lower_b_true = [m[2] for m in y_true]
upper_b_pred = [m[0] for m in y_pred]
y_med_pred = [m[1] for m in y_pred]
lower_b_pred = [m[2] for m in y_pred]
#MSE part
err = y_med_true - y_med_pred
mse_loss = tf.math.reduce_mean(tf.math.square(err))
#Narrow bound
bound_dif = upper_b_pred - lower_b_pred
bound_loss = tf.math.reduce_mean(bound_dif)
#Prob metric
in_upper = y_med_pred <= upper_b_pred
in_lower = y_med_pred >= lower_b_pred
prob = tf.logical_and(in_upper,in_lower)
prob = tf.math.reduce_mean(tf.where(prob,1.0,0.0))
return mse_loss + tf.multiply(tr1, bound_loss) + tf.multiply(tr2, prob)
我试图在执行它的同时对它进行部分注解,但我认为问题出在我提到的列表压缩部分。
1条答案
按热度按时间l5tcr1uw1#
您应该使用tf.unstack:
将给定维数的秩-RTensor分解为秩-(R-1)Tensor。