news 2026/3/5 0:28:08

深度学习中的K-Fold交叉验证

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
深度学习中的K-Fold交叉验证

交叉验证是一种用于评估深度学习模型性能的统计方法。交叉验证是一种重采样方法,用于在有限的数据样本上评估深度学习模型,可用于分类、回归等任务。交叉验证可以减少过拟合、提供稳健的性能评估、高效利用数据(尤其是在数据量有限的情况下)。

K-Fold Cross-Validation:K折交叉验证,K表示给定数据样本随机要分成的大小相等的组数(折)。训练K次,将模型在所有K次迭代中的性能取平均值,从而得到模型泛化能力的估计。如下图所示:原图来自于: https://www.kaggle.com

一般步骤:数据集中的每个样本有且仅一次用于测试,每个样本均K-1次用于训练

1. 随机打乱数据集,将数据集分成K折。

2. 训练及测试:对于每个折,使用K-1个折来训练模型,使用剩余的折作为测试集来评估模型。

3. 汇总结果:计算每个折的性能指标,并取平均值。

K值的选择会影响偏差和方差之间的权衡,K的选择通常为5或10,没有硬性规定。小数据集适合较大的K值,中数据集适合较小的K值。大数据集不建议使用K-Fold。

1. 较小的K值,使计算速度更快,但性能估计的方差更大。

2. 较大的K值,使方差更小,但计算成本更高。

以下测试代码为将数据集按照K折交叉验证拆分,并计算mean和std,用于回归训练中,csv文件中为每幅图像对应一个float值

def parse_args(): parser = argparse.ArgumentParser(description="K-Fold Cross-Validation") parser.add_argument("--src_dataset_path", required=True, type=str, help="source dataset path") parser.add_argument("--src_csv_file", required=True, type=str, help="source csv file") parser.add_argument("--dst_dataset_path", required=True, type=str, help="the path of the destination dataset after split") parser.add_argument("--k", type=int, default=5, help="number fo groups, K-Fold cross validataion") args = parser.parse_args() return args def split_k_fold(src_dataset_path, dst_dataset_path, src_csv_file, k): if src_dataset_path is None or not src_dataset_path or not Path(src_dataset_path).is_dir(): raise ValueError(colorama.Fore.RED + f"{src_dataset_path} is not a directory") if src_csv_file is None or not src_csv_file or not Path(src_csv_file).is_file(): raise ValueError(colorama.Fore.RED + f"{src_csv_file} is not a file") for i in range(1, k+1): path_name = dst_dataset_path + "_" + str(i) if Path(path_name).exists(): raise FileExistsError(colorama.Fore.RED + f"specified directory already exists: {path_name}") Path(path_name).mkdir(parents=True) Path(path_name + "/train").mkdir(parents=True) Path(path_name + "/val").mkdir(parents=True) dataframe = pd.read_csv(src_csv_file, header=None) samples = dataframe.values.tolist() if len(samples) == 0: raise FileNotFoundError(colorama.Fore.RED + f"there is no data in the file: {src_csv_file}") print(f"samples length: {len(samples)}; samples0: {samples[0]}") images = [img for img in Path(src_dataset_path).glob("*") if img.is_file()] if len(images) == 0: raise FileNotFoundError(colorama.Fore.RED + f"there are no matching images in this directory: {src_dataset_path}") print(f"images number: {len(images)}, image0: {images[0]}") if len(samples) != len(images): raise ValueError(colorama.Fore.RED + f"length mismatch: samples:{len(samples)}; images:{len(images)}") for i in range(0, len(samples)): if samples[i][2] != images[i].name: raise ValueError(colorama.Fore.RED + f"name mismatch: samples{i}:{samples[i][2]}; images{i}:{images[i].name}") total = len(samples) numbers = list(range(total)) random.shuffle(numbers) fold_size = total // k def write_and_copy(index_list, folder, csv_file): with open(csv_file, mode="w", newline="", encoding="utf-8") as file: write = csv.writer(file) for idx in index_list: write.writerow(samples[idx]) shutil.copy(images[idx], folder) def calculate_mean_std(train_list, txt_file): mean_sum = np.zeros(3, dtype=np.float64) std_sum = np.zeros(3, dtype=np.float64) for idx in train_list: img = cv2.imread(str(images[idx])) if img is None: raise FileNotFoundError(colorama.Fore.RED + f"image file does not exist: {images[idx]}") img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = img.astype(np.float64) / 255.0 mean_sum += img.mean(axis=(0, 1)) std_sum += img.std(axis=(0, 1)) mean = mean_sum / len(train_list) std = std_sum / len(train_list) with open(txt_file, mode="w", encoding="utf-8") as file: file.write(f'--mean "{tuple(mean.tolist())}" --std "{tuple(std.tolist())}"') for fold in range(k): val_idx = numbers[fold * fold_size : (fold + 1) * fold_size] if fold < k - 1 else numbers[fold * fold_size :] train_idx = [i for i in numbers if i not in val_idx] print(f"fold {fold + 1}: length val: {len(val_idx)}; train: {len(train_idx)}") write_and_copy(train_idx, dst_dataset_path + "_" + str(fold+1) + "/train", dst_dataset_path + "_" + str(fold+1) + "/train.csv") write_and_copy(val_idx, dst_dataset_path + "_" + str(fold+1) + "/val", dst_dataset_path + "_" + str(fold+1) + "/val.csv") calculate_mean_std(train_idx, dst_dataset_path + "_" + str(fold+1) + "/mean_std.txt") if __name__ == "__main__": colorama.init(autoreset=True) args = parse_args() split_k_fold(args.src_dataset_path, args.dst_dataset_path, args.src_csv_file, args.k) print(colorama.Fore.GREEN + "====== execution completed ======")

执行结果如下图所示:

GitHub:https://github.com/fengbingchun/NN_Test

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/3/4 14:20:06

goroutine 栈是如何“自动扩容”的?

前言goroutine 初始栈很小(≈2KB)&#xff0c;但可以自动变大。那它是怎么做到的&#xff1f;一、先说结论 goroutine 的栈扩容是通过&#xff1a;在函数调用前做“栈空间检查”&#xff0c;如果不够&#xff0c;就调用 runtime 进行扩容。关键机制是&#xff1a; stack guard …

作者头像 李华
网站建设 2026/3/4 21:06:21

2026年AI智能产品开发领域十大资质审核通过的企业

2026年AI智能产品开发&#xff1a;十大专业服务商深度解析在数字化转型的浪潮中&#xff0c;企业对AI智能产品开发的需求日益增长。然而&#xff0c;如何从众多服务商中找到适合自己的合作伙伴&#xff1f;本文将通过技术实力、行业适配性和客户反馈三个维度&#xff0c;推荐十…

作者头像 李华
网站建设 2026/3/4 8:07:02

快手因低俗内容被罚1.19亿 回应称教训极其惨痛,将以此为戒

雷递网 乐天 2月7日2月6日&#xff0c;北京市互联网信息办公室依据《中华人民共和国网络安全法》《中华人民共和国行政处罚法》等法律法规&#xff0c;对北京快手科技有限公司处警告、1.191亿元罚款处罚&#xff0c;同时责令其限期改正、依法依约处置账号、从严处理责任人。事情…

作者头像 李华
网站建设 2026/3/4 21:46:00

ClickHouse 索引优化:提升大数据查询速度的秘诀

ClickHouse 索引优化&#xff1a;提升大数据查询速度的秘诀 关键词&#xff1a;ClickHouse、索引优化、大数据查询、稀疏索引、数据分区、数据排序、查询优化 摘要&#xff1a;本文深入解析ClickHouse索引体系的核心原理&#xff0c;通过稀疏索引、数据分区、排序键设计等关键技…

作者头像 李华
网站建设 2026/3/4 12:37:35

Qwen3-ASR-1.7B快速上手:音频时长限制与分段处理策略

Qwen3-ASR-1.7B快速上手&#xff1a;音频时长限制与分段处理策略 1. 引言 语音识别技术正在改变我们处理音频内容的方式。Qwen3-ASR-1.7B作为阿里通义千问推出的端到端语音识别模型&#xff0c;凭借其17亿参数和多语言支持能力&#xff0c;为开发者提供了强大的离线转写工具。…

作者头像 李华
网站建设 2026/3/4 12:55:42

AI头像生成器技术揭秘:深度学习模型架构解析

AI头像生成器技术揭秘&#xff1a;深度学习模型架构解析 1. 从一张照片到惊艳头像&#xff1a;我们到底在用什么技术 你有没有试过上传一张普通自拍照&#xff0c;几秒钟后就得到一张专业级的肖像&#xff1f;不是简单地加滤镜&#xff0c;而是连发丝纹理、皮肤质感、光影层次…

作者头像 李华