Python實現數據集自動劃分的示例代碼(訓練集/驗證集/測試集)
在深度學習模型訓練中,我們通常需要將數據集劃分為訓練集(Train)、驗證集(Val)和測試集(Test)。訓練集用于模型參數學習,驗證集用于超參數調優(yōu),測試集用于評估模型最終泛化能力。手動劃分不僅效率低,還難以保證隨機性,這里分享一段自動劃分數據集的 Python 腳本。
代碼功能說明
這段代碼的核心功能是:將原始數據集中的圖片和對應標簽,按照 8:1:1 的比例隨機劃分為訓練集、驗證集和測試集,并分別存放于對應目錄中,同時保證劃分結果可復現。
代碼如下
import os
import random
import shutil
# 分割訓練集和驗證集
# 設置隨機種子以保證結果可復現
random.seed(42)
# 數據集根目錄
data_dir = './datasets'
images_dir = os.path.join(data_dir, 'images')
labels_dir = os.path.join(data_dir, 'labels')
# 創(chuàng)建目錄
os.makedirs(os.path.join(images_dir, 'train'), exist_ok=True)
os.makedirs(os.path.join(images_dir, 'val'), exist_ok=True)
os.makedirs(os.path.join(labels_dir, 'train'), exist_ok=True)
os.makedirs(os.path.join(labels_dir, 'val'), exist_ok=True)
os.makedirs(os.path.join(images_dir, 'test'), exist_ok=True)
os.makedirs(os.path.join(labels_dir, 'test'), exist_ok=True)
# 獲取所有的圖像文件名
image_files = [f for f in os.listdir(os.path.join(data_dir, 'images')) if f.endswith('.jpg')]
# 計算訓練集和驗證集的大小
train_ratio = 0.8
val_ratio = 0.1
test_ratio = 0.1
total_images = len(image_files)
train_index = int(total_images * train_ratio)
val_index = int(total_images * (train_ratio + val_ratio))
# 打亂文件列表
random.shuffle(image_files)
# 劃分數據集
train_images = image_files[:train_index]
val_images = image_files[train_index:val_index]
test_images = image_files[val_index:]
for img_file in train_images:
label_file = img_file.replace('.jpg', '.txt')
shutil.copy(os.path.join(data_dir, 'images', img_file), os.path.join(images_dir, 'train'))
shutil.copy(os.path.join(data_dir, 'labels', label_file), os.path.join(labels_dir, 'train'))
for img_file in val_images:
label_file = img_file.replace('.jpg', '.txt')
shutil.copy(os.path.join(data_dir, 'images', img_file), os.path.join(images_dir, 'val'))
shutil.copy(os.path.join(data_dir, 'labels', label_file), os.path.join(labels_dir, 'val'))
for img_file in test_images:
label_file = img_file.replace('.jpg', '.txt')
shutil.copy(os.path.join(data_dir, 'images', img_file), os.path.join(images_dir, 'test'))
shutil.copy(os.path.join(data_dir, 'labels', label_file), os.path.join(labels_dir, 'test'))
print(f"數據集劃分完成!訓練集: {len(train_images)},驗證集: {len(val_images)},測試集: {len(test_images)}")
import sys
sys.exit(0)代碼解析
1. 導入依賴庫
首先導入必要的 Python 庫,os用于文件路徑操作,random用于隨機打亂文件列表,shutil用于文件復制:
import os import random import shutil
2. 保證結果可復現
設置隨機種子,確保每次運行代碼的劃分結果一致(便于實驗對比):
random.seed(42) # 固定種子,結果可復現
3. 目錄設置與創(chuàng)建
定義數據集根目錄及圖片、標簽存放路徑,并自動創(chuàng)建劃分后的子目錄(train/val/test):
# 數據集根目錄 data_dir = './datasets' images_dir = os.path.join(data_dir, 'images') # 原始圖片目錄 labels_dir = os.path.join(data_dir, 'labels') # 原始標簽目錄 # 創(chuàng)建劃分后的子目錄(若已存在則不報錯) os.makedirs(os.path.join(images_dir, 'train'), exist_ok=True) os.makedirs(os.path.join(images_dir, 'val'), exist_ok=True) os.makedirs(os.path.join(images_dir, 'test'), exist_ok=True) os.makedirs(os.path.join(labels_dir, 'train'), exist_ok=True) os.makedirs(os.path.join(labels_dir, 'val'), exist_ok=True) os.makedirs(os.path.join(labels_dir, 'test'), exist_ok=True)
4. 讀取與劃分文件
獲取所有圖片文件,按比例劃分并隨機打亂:
# 獲取所有.jpg格式的圖片文件(可根據實際格式修改)
image_files = [f for f in os.listdir(images_dir) if f.endswith('.jpg')]
# 定義劃分比例(可根據需求調整)
train_ratio = 0.8 # 訓練集占比
val_ratio = 0.1 # 驗證集占比
test_ratio = 0.1 # 測試集占比
# 計算各集合的文件數量
total_images = len(image_files)
train_index = int(total_images * train_ratio) # 訓練集結束索引
val_index = int(total_images * (train_ratio + val_ratio)) # 驗證集結束索引
# 隨機打亂文件列表(保證劃分隨機性)
random.shuffle(image_files)
# 劃分數據集
train_images = image_files[:train_index] # 訓練集
val_images = image_files[train_index:val_index] # 驗證集
test_images = image_files[val_index:] # 測試集
5. 復制文件到對應目錄
將圖片和對應的標簽文件(假設標簽與圖片同名,后綴為.txt)復制到劃分后的目錄:
# 復制訓練集文件
for img_file in train_images:
label_file = img_file.replace('.jpg', '.txt') # 標簽文件名(與圖片對應)
shutil.copy(os.path.join(images_dir, img_file), os.path.join(images_dir, 'train'))
shutil.copy(os.path.join(labels_dir, label_file), os.path.join(labels_dir, 'train'))
# 復制驗證集文件(邏輯同上)
for img_file in val_images:
label_file = img_file.replace('.jpg', '.txt')
shutil.copy(os.path.join(images_dir, img_file), os.path.join(images_dir, 'val'))
shutil.copy(os.path.join(labels_dir, label_file), os.path.join(labels_dir, 'val'))
# 復制測試集文件(邏輯同上)
for img_file in test_images:
label_file = img_file.replace('.jpg', '.txt')
shutil.copy(os.path.join(images_dir, img_file), os.path.join(images_dir, 'test'))
shutil.copy(os.path.join(labels_dir, label_file), os.path.join(labels_dir, 'test'))
6. 輸出劃分結果
打印各集合的文件數量,確認劃分完成:
print(f"數據集劃分完成!訓練集: {len(train_images)},驗證集: {len(val_images)},測試集: {len(test_ima使用說明
- 目錄結構要求:原始數據集需按如下結構存放(可修改代碼中
data_dir路徑適配你的數據):
datasets/ ├─ images/ # 存放所有圖片(.jpg格式) └─ labels/ # 存放所有標簽(.txt格式,與圖片同名)
- 格式適配:若圖片格式為.png 等,需修改
endswith('.jpg')為對應格式;標簽格式不同時同理。 - 比例調整:修改
train_ratio、val_ratio、test_ratio可自定義劃分比例。
以上就是Python實現數據集自動劃分的示例代碼(訓練集/驗證集/測試集)的詳細內容,更多關于Python數據集自動劃分的資料請關注腳本之家其它相關文章!
相關文章
Python3 執(zhí)行系統(tǒng)命令并獲取實時回顯功能
這篇文章主要介紹了Python3 執(zhí)行系統(tǒng)命令并獲取實時回顯功能,文中通過兩種方法給大家介紹了Python執(zhí)行系統(tǒng)命令并獲得輸出的方法,需要的朋友可以參考下2019-07-07
解決tensorflow訓練時內存持續(xù)增加并占滿的問題
今天小編就為大家分享一篇解決tensorflow訓練時內存持續(xù)增加并占滿的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01

