用于多类物体检测的分层K形折叠?

如何解决用于多类物体检测的分层K形折叠?

已更新

我已经上传了一个虚拟数据集,链接heredf.head()

enter image description here

它总共有 4个班级df.object.value_counts()

human    23
car      13
cat       5
dog       3

我想正确地进行K-Fold验证,以对多类对象检测数据集进行分割。

初始方法

为了实现适当的k倍验证拆分,我考虑了object countsbounding 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

拆分后,我检查了一下是否可以正常使用。到目前为止看来还可以。

enter image description here

所有折痕均包含分层的k-fold个样本len(df_folds[df_folds['fold'] == fold_number].index),并且彼此没有交集,set(A).intersection(B),其中AB是索引值({ {1}})的两倍。但问题似乎是:

image_id

关注

但是,我无法确定这通常是否适合此类任务。我想要一些建议。上面的方法可以吗?或任何问题?还是有更好的方法!任何形式的建议将不胜感激。谢谢。

解决方法

在创建交叉验证拆分时,我们关心的是创建折叠,这些折叠具有良好分布的数据中遇到的各种“案例”。

在您的情况下,您决定根据汽车的数量和边界框的数量来确定折页数,这是一个不错的选择,但选择有限。因此,如果您可以使用数据/元数据识别特定情况,则可以尝试使用它创建更智能的折叠。

最明显的选择是在折叠中平衡对象类型(类),但是您可以走得更远。

这里是主要思想,假设您有一些图像,其中大多数在法国遇到汽车,而其他一些在美国遇到汽车,则可以用来制作折页,每张折折的法国和美国汽车数量均折。在天气等情况下也可以这样做。因此,每个折叠都将包含有代表性的数据以供学习,这样您的网络就不会因您的任务而有偏差。这样一来,您的模型将对数据中的此类潜在现实生活变化更加健壮。

那么,您可以在交叉验证策略中添加一些元数据以创建更好的简历吗?如果不是这种情况,是否可以使用数据集的x,y,w,h列获取有关潜在极端情况的信息?

然后,您应尝试使样本的折痕平衡,以便在相同的样本量下评估分数,这将减少差异并最终提供更好的评​​估。

,

您可以直接使用StratifiedKFold()或StratifiedShuffleSplit()来基于某些分类列使用分层抽样来拆分数据集。

虚拟数据:

import pandas as pd
import numpy as np

np.random.seed(43)
df = pd.DataFrame({'ID': (1,1,2,3,3),'Object': ('bus','car','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,strat_test_set)
,

我只需使用scikit learning的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]))

,请查看Jimp是否有帮助

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-