python - 两个段上联合的交集
问题描述
假设我有这两个 Dataframes :Groundtruth和Prediction。
每个 Dataframe 有 3 列;行动,开始和结束。
**Prediction :**
Action | Start | End
-------------------------
3 | 0 | 10
2 | 10 | 70
3 | 80 | 120
0 | 120 | 350
7 | 400 | 610
...
**Groundtruth :**
Action | Start | End
-------------------------
2 | 20 | 140
0 | 150 | 340
6 | 420 | 600
...
我想使用所有列在这两个数据帧上计算交集比联合(IoU),这意味着首先操作以查看它是否是正确的预测,再加上每个操作的开始和结束段以查看是否正确开始和结束.
这是我的代码:
def compute_iou(y_pred, y_true):
y_pred = y_pred.flatten()
y_true = y_true.flatten()
cm = confusion_matrix(y_true, y_pred)
intersection = np.diag(cm)
ground_truth_set = cm.sum(axis=1)
predicted_set = cm.sum(axis=0)
union = ground_truth_set + predicted_set - intersection
IoU = intersection / union
for i in range(len(IoU)):
if (IoU[i]>0.5):
IoU[i] = 1
return round(np.mean(IoU)*100, 3)
当我想在操作列上计算 IoU 时,这很有效。
现在我该如何调整它,以便我可以让 IoU 在开始列和结束列上获得重叠段?
PS:Groundtruth 和 Prediction 数据帧的行数不同。
解决方案
(后期编辑)
计算分为三种情况:
- 重叠:活动匹配的地方,并且在地面实况区间和预测区间之间存在重叠。
- 没有重叠:活动匹配,但没有这样的重叠。
- 没有命中:根本没有预测到活动,或者有错误的活动。
这是代码:
df = pd.merge(pred, groundtruth, on = "Action", how = "outer", suffixes = ["_pred", "_gt"])
overlap = df[(df.Start_pred < df.End_gt) & (df.Start_gt < df.End_pred)]
intersection = (overlap[["End_pred", "End_gt"]].min(axis=1) - overlap[["Start_pred", "Start_gt"]].max(axis=1)).sum()
union_where_overlap = (overlap[["End_pred", "End_gt"]].max(axis=1) - overlap[["Start_pred", "Start_gt"]].\
min(axis=1)).sum()
no_hit = df[df.isna().sum(axis=1) > 0]
union_no_hit = (no_hit[["End_pred", "End_gt"]].max(axis=1) - no_hit[["Start_pred", "Start_gt"]].min(axis=1)).sum()
no_overlap = df[~((df.Start_pred < df.End_gt) & (df.Start_gt < df.End_pred))].dropna()
union_no_overlap = ((no_overlap.End_pred - no_overlap.Start_pred) + (no_overlap.End_gt - no_overlap.Start_gt)).sum()
IoU = intersection / (union_no_hit + union_where_overlap + union_no_overlap)
推荐阅读
- java - 当测试预期异常时,assertEquals 不显示错误
- php - 如何在 macOS 10.14.1 Mojave 中安装带有对 php 的 freetype 支持的 GD
- python - Add one column dor each value in a list
- javascript - 将变量绑定到对象属性
- php - 如何对文本框进行分组,以便同时提交它们。使用 PHP、CodeIgniter 和 HTML
- c++ - CV_LOAD_IMAGE_GRAYSCALE 和 cvtCOLOR(..., BGR2GRAY) 之间的区别
- ruby-on-rails - 在 Rails 路由中使用 lambda 在“get”下嵌套“get”请求
- java - Config-Server 无法配置数据源:未指定“url”属性,无法配置嵌入式数据源
- typescript - 打字稿:具有名称 getter / setter 属性的类
- javascript - 在 div 中包装复选框会破坏 javascript