最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python實現數據集自動劃分的示例代碼(訓練集/驗證集/測試集)

 更新時間:2026年04月02日 09:41:16   作者:CV小涵  
本文提供了一段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

使用說明

  1. 目錄結構要求:原始數據集需按如下結構存放(可修改代碼中data_dir路徑適配你的數據):
datasets/
├─ images/  # 存放所有圖片(.jpg格式)
└─ labels/  # 存放所有標簽(.txt格式,與圖片同名)
  1. 格式適配:若圖片格式為.png 等,需修改endswith('.jpg')為對應格式;標簽格式不同時同理。
  2. 比例調整:修改train_ratio、val_ratio、test_ratio可自定義劃分比例。

以上就是Python實現數據集自動劃分的示例代碼(訓練集/驗證集/測試集)的詳細內容,更多關于Python數據集自動劃分的資料請關注腳本之家其它相關文章!

相關文章

  • Python當中的array數組對象實例詳解

    Python當中的array數組對象實例詳解

    這篇文章主要介紹了Python當中的array數組對象,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值 ,需要的朋友可以參考下
    2019-06-06
  • python使用opencv讀取圖片的實例

    python使用opencv讀取圖片的實例

    下面小編就為大家?guī)硪黄猵ython使用opencv讀取圖片的實例。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-08-08
  • Python3 執(zhí)行系統(tǒng)命令并獲取實時回顯功能

    Python3 執(zhí)行系統(tǒng)命令并獲取實時回顯功能

    這篇文章主要介紹了Python3 執(zhí)行系統(tǒng)命令并獲取實時回顯功能,文中通過兩種方法給大家介紹了Python執(zhí)行系統(tǒng)命令并獲得輸出的方法,需要的朋友可以參考下
    2019-07-07
  • 詳解Python中的join()函數的用法

    詳解Python中的join()函數的用法

    這篇文章主要介紹了詳解Python中的join()函數的用法,join()函數主要用來拼接字符串,是Python學習當中的基礎知識,需要的朋友可以參考下
    2015-04-04
  • python模擬鍵盤輸入 切換鍵盤布局過程解析

    python模擬鍵盤輸入 切換鍵盤布局過程解析

    這篇文章主要介紹了python模擬鍵盤輸入 切換鍵盤布局過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-08-08
  • centos安裝python3.10的教程

    centos安裝python3.10的教程

    文章主要介紹了在CentOS系統(tǒng)上安裝Python 3.10.1的步驟,包括升級OpenSSL到1.1.1,以及詳細的操作過程,如切換目錄、下載安裝包、解壓、配置、編譯安裝、創(chuàng)建軟連接和驗證等
    2025-03-03
  • 手把手帶你了解Python數據分析--matplotlib

    手把手帶你了解Python數據分析--matplotlib

    這篇文章主要介紹了Python實現matplotlib顯示中文的方法,結合實例形式詳細總結分析了Python使用matplotlib庫繪圖時顯示中文的相關操作技巧與注意事項,需要的朋友可以參考下
    2021-08-08
  • 解決tensorflow訓練時內存持續(xù)增加并占滿的問題

    解決tensorflow訓練時內存持續(xù)增加并占滿的問題

    今天小編就為大家分享一篇解決tensorflow訓練時內存持續(xù)增加并占滿的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • 如何將json數據轉換為python數據

    如何將json數據轉換為python數據

    這篇文章主要介紹了如何將json數據轉換為python數據,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-09-09
  • 關于Python中字符串的各種操作

    關于Python中字符串的各種操作

    本文將重點介紹Python字符串的各種常用方法,字符串是實際開發(fā)中經常用到的,所有熟練的掌握它的各種用法顯得尤為重要。需要的朋友可以參考下面文章內容
    2021-09-09

最新評論

凌云县| 江都市| 新津县| 苏尼特右旗| 崇义县| 威远县| 临沭县| 海淀区| 越西县| 丹东市| 贵定县| 都江堰市| 商城县| 元谋县| 德兴市| 黔西县| 永安市| 凤冈县| 丘北县| 寿光市| 平安县| 眉山市| 金阳县| 罗田县| 安阳县| 旬阳县| 青河县| 长子县| 肇州县| 义乌市| 调兵山市| 新安县| 衢州市| 措勤县| 岱山县| 思南县| 金华市| 金沙县| 中超| 库尔勒市| 高要市|