mlR*_*cks 8 python machine-learning deep-learning keras tensorflow
我正在参加Kaggle的竞赛,评估指标定义为
该竞争是根据不同交叉点上的平均精度(IoU)阈值来评估的.建议的一组对象像素和一组真实对象像素的IoU计算如下:
IoU(A,B)=(A?B)/(A?B)
Run Code Online (Sandbox Code Playgroud)
度量标准扫描一系列IoU阈值,在每个点计算平均精度值.阈值范围从0.5到0.95,步长为0.05 : (0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95)
. 换句话说,在阈值为0.5时,如果预测对象与地面实况对象结合的交点大于0.5,则认为该预测对象是"命中".在每个阈值t处,基于通过将预测对象与所有地面实况对象进行比较而得到的真阳性(TP)
,假阴性(FN)
和误报的数量来计算精度值(FP)
:
TP(t)/TP(t)+FP(t)+FN(t).
Run Code Online (Sandbox Code Playgroud)
当单个预测对象与IoU高于阈值的地面实况对象匹配时,计算真正的正数.误报表示预测对象没有关联的地面实况对象.假阴性表示地面实况对象没有关联的预测对象.然后将单个图像的平均精度计算为每个IoU阈值处的上述精度值的平均值:
(1/|thresholds|)*?tTP(t)/TP(t)+FP(t)+FN(t)
Run Code Online (Sandbox Code Playgroud)
现在,我已经在纯粹的numpy中编写了这个函数,因为它更容易编码,我已经装饰它tf.py_fucn()
以便与Keras一起使用.以下是示例代码:
def iou_metric(y_true_in, y_pred_in, fix_zero=False):
labels = y_true_in
y_pred = y_pred_in
true_objects = 2
pred_objects = 2
if fix_zero:
if np.sum(y_true_in) == 0:
return 1 if np.sum(y_pred_in) == 0 else 0
intersection = np.histogram2d(labels.flatten(), y_pred.flatten(), bins=(true_objects, pred_objects))[0]
# Compute areas (needed for finding the union between all objects)
area_true = np.histogram(labels, bins = true_objects)[0]
area_pred = np.histogram(y_pred, bins = pred_objects)[0]
area_true = np.expand_dims(area_true, -1)
area_pred = np.expand_dims(area_pred, 0)
# Compute union
union = area_true + area_pred - intersection
# Exclude background from the analysis
intersection = intersection[1:,1:]
union = union[1:,1:]
union[union == 0] = 1e-9
# Compute the intersection over union
iou = intersection / union
# Precision helper function
def precision_at(threshold, iou):
matches = iou > threshold
true_positives = np.sum(matches, axis=1) == 1 # Correct objects
false_positives = np.sum(matches, axis=0) == 0 # Missed objects
false_negatives = np.sum(matches, axis=1) == 0 # Extra objects
tp, fp, fn = np.sum(true_positives), np.sum(false_positives), np.sum(false_negatives)
return tp, fp, fn
# Loop over IoU thresholds
prec = []
for t in np.arange(0.5, 1.0, 0.05):
tp, fp, fn = precision_at(t, iou)
if (tp + fp + fn) > 0:
p = tp / (tp + fp + fn)
else:
p = 0
prec.append(p)
return np.mean(prec)
Run Code Online (Sandbox Code Playgroud)
我试图将它转换为纯tf
函数,但无法做到,因为我无法弄清楚它是如何control dependencies
工作的.任何人都可以帮助我吗?
要使用你的函数,你必须转换张量和 numpy 数组,反之亦然。要将张量转换为 numpy 数组,请使用tf.eval
(请参阅此处):
np_array = tensor.eval()
Run Code Online (Sandbox Code Playgroud)
如果你想将 python 对象(也是 numpy 数组)转换为张量,你可以使用tf.convert_to_tensor
(参见这里):
tensor = tf.convert_to_tensor(np.mean(prec),dtype=tf.float32)
Run Code Online (Sandbox Code Playgroud)