用于多类目标检测的分层 K 折叠?
Posted
技术标签:
【中文标题】用于多类目标检测的分层 K 折叠?【英文标题】:Stratified K-Fold For Multi-Class Object Detection? 【发布时间】:2021-01-17 17:46:01 【问题描述】:更新
我上传了一个虚拟数据集,链接here。 df.head()
:
共有4类,df.object.value_counts()
:
human 23
car 13
cat 5
dog 3
我想在多类对象检测数据集上正确地进行K-Fold
验证拆分。
初步方法
为了实现正确的 k-fold 验证拆分,我考虑了 object counts
和 bounding box
的数量。我了解,K-fold
拆分策略主要取决于数据集(元信息)。但是现在对于这些数据集,我尝试了如下方法:
skf = StratifiedKFold(n_splits=3, shuffle=True, random_state=101)
df_folds = main_df[['image_id']].copy()
df_folds.loc[:, 'bbox_count'] = 1
df_folds = df_folds.groupby('image_id').count()
df_folds.loc[:, 'object_count'] = main_df.groupby('image_id')['object'].nunique()
df_folds.loc[:, 'stratify_group'] = np.char.add(
df_folds['object_count'].values.astype(str),
df_folds['bbox_count'].apply(lambda x: f'_x // 15').values.astype(str)
)
df_folds.loc[:, 'fold'] = 0
for fold_number, (train_index, val_index) in enumerate(skf.split(X=df_folds.index, y=df_folds['stratify_group'])):
df_folds.loc[df_folds.iloc[val_index].index, 'fold'] = fold_number
拆分后,我检查了它是否正常工作。到目前为止看起来还不错。
所有折叠都包含分层的k-fold
样本,len(df_folds[df_folds['fold'] == fold_number].index)
并且彼此没有交集,set(A).intersection(B)
其中A
和B
是两个折叠的索引值(image_id
)。但问题似乎是:
Fold 0 has total: 18 + 2 + 3 = 23 bbox
Fold 1 has total: 2 + 11 = 13 bbox
Fold 2 has total: 5 + 3 = 8 bbox
关注
但是,我无法确定这是否适合这种类型的任务。我想要一些建议。上述方法可以吗?或任何问题?或者有更好的方法!任何形式的建议将不胜感激。谢谢。
【问题讨论】:
【参考方案1】:在创建交叉验证拆分时,我们关心的是创建折叠,以使数据中遇到的各种“案例”分布良好。
在您的情况下,您决定根据汽车的数量和边界框的数量来折叠,这是一个不错但有限的选择。因此,如果您可以使用您的数据/元数据识别特定案例,您可能会尝试使用它创建更智能的折叠。
最明显的选择是平衡折叠中的对象类型(类),但您可以更进一步。
这是主要的想法,假设您的图片主要是在法国遇到的汽车,而其他图片主要是在美国遇到的汽车,它可以用来创建良好的折叠,其中法国和美国汽车的数量平衡折叠。天气条件等也可以这样做。因此,每个折叠都将包含要从中学习的代表性数据,这样您的网络就不会因您的任务而产生偏见。因此,您的模型将对数据中这种潜在的现实生活变化更加稳健。
那么,您能否在交叉验证策略中添加一些元数据来创建更好的简历?如果不是这样,您能否使用数据集的 x、y、w、h 列获取有关潜在极端情况的信息?
然后您应该尝试在样本方面进行平衡折叠,以便在相同的样本量上评估您的分数,这将减少方差并在最后提供更好的评估。
【讨论】:
感谢您的建议。在所有给出的答案中,这个答案在赏金奖励时间表内足够接近。但如果它也有一些最低限度的代码演示,我会标记为正确答案。【参考方案2】:您可以使用 StratifiedKFold() 或 StratifiedShuffleSplit() 直接使用基于某些分类列的分层抽样来拆分数据集。
虚拟数据:
import pandas as pd
import numpy as np
np.random.seed(43)
df = pd.DataFrame('ID': (1,1,2,2,3,3),
'Object': ('bus', 'car', 'bus', 'bus', 'bus', 'car'),
'X' : np.random.randint(0, 10, 6),
'Y' : np.random.randn(6)
)
df
使用 StratifiedKFold()
from sklearn.model_selection import StratifiedKFold
skf = StratifiedKFold(n_splits=2)
for train_index, test_index in skf.split(df, df["Object"]):
strat_train_set_1 = df.loc[test_index]
strat_test_set_1 = df.loc[test_index]
print('train_set :', strat_train_set_1, '\n' , 'test_set :', strat_test_set_1)
同样,如果你选择使用 StratifiedShuffleSplit(),你可以有
from sklearn.model_selection import StratifiedShuffleSplit
sss = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
# n_splits = Number of re-shuffling & splitting iterations.
for train_index, test_index in sss.split(df, df["Object"]):
# split(X, y[, groups]) Generates indices to split data into training and test set.
strat_train_set = df.loc[train_index]
strat_test_set = df.loc[test_index]
print('train_set :', strat_train_set, '\n' , 'test_set :', strat_test_set)
【讨论】:
感谢您的评论。但是,我认为您误解了我的查询。我不在乎使用StratifiedKFold()
或StratifiedShuffleSplit()
。我关心的是为多类对象检测制定适当的验证策略。为此,我的方法是考虑object
的类型和bbox
的数量。但是,如果您在我的查询中看到我已经在使用 StratifiedKFold()
。【参考方案3】:
我会简单地使用 python 的 scikit-learn 的 KFold
方法来做到这一点
from numpy import array
from sklearn.model_selection import KFold
data = array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6])
kfold = KFold(3, True, 1)
for train, test in kfold.split(data):
print('train: %s, test: %s' % (data[train], data[test]))
请查看this 是否有帮助
【讨论】:
你能解释一下为什么你会直接使用“KFold”而不考虑后果吗? @M.Innat 有什么后果?以上是关于用于多类目标检测的分层 K 折叠?的主要内容,如果未能解决你的问题,请参考以下文章
何恺明团队新作:只用普通ViT,不做分层设计也能搞定目标检测
第31篇探索普通视觉Transformer Backbones用于物体检测