我想建立一个具有公差的自定义精度指标。如果在给定的公差值之内两个元素的差值一致,则此精度将计数这两个元素的一致性,而不是对y_true
和中的元素完全相等y_pred
。例如,如果预测度与真实度之差小于5度,我们可以认为结果正确,并根据此规则计算准确性。我想使用此指标,model.compile
因此它应该是可调用的函数。
我写了一个函数如下。
def accuracy_with_tolerence(y_true,y_pred):
"""
y_true/y_pred: batch of samples; (BatchSize, 1)
"""
threshold = 5
differnece = tf.abs(tf.subtract(y_true,y_pred)) - threshold
boolean_results = [True if i < 0 else False for i in differnece]
return K.mean(math_ops.cast(boolean_results, K.floatx()))
它可以返回正确的精度值。
x = tf.constant([1, 2, 3], dtype=tf.float32)
y = tf.constant([5, 8, 10], dtype=tf.float32)
acc = accuracy_with_tolerence(x,y)
print(acc)
tf.Tensor(0.33333334, shape=(), dtype=float32)
但是当我想在编译中使用它时,会出现错误:
# Initialize ResNet50
model = resnet50()
model.compile(optimizer='adam',loss='mse',metrics=[accuracy_with_tolerence])
model.load_weights(checkpoint_filepath_0)
model.evaluate(x_test,y_test)
OperatorNotAllowedInGraphError: iterating over `tf.Tensor` is not allowed: AutoGraph did convert this function. This might indicate you are trying to use an unsupported feature.
看来我无法迭代张量。那么如何在度量函数中获得按元素进行布尔比较的结果呢?如何实现此精度功能?
先感谢您。
您无法使用张量进行列表理解。您正在寻找的操作是tf.where
,您可以按以下方式使用它:
def accuracy_with_tolerence(y_true, y_pred):
threshold = 5
differnece = tf.abs(tf.subtract(y_true, y_pred)) - threshold
boolean_results = tf.where(differnece>0, True, False)
return K.mean(math_ops.cast(boolean_results, K.floatx()))
请注意,您可以进一步简化代码:
...
boolean_results = tf.where(tf.abs(tf.subtract(y_true, y_pred)) - threshold>0, 1., 0.)
return K.mean(boolean_results)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句