如何随机划分图片形式的数据集,训练集和测试集的比例为9:1
时间: 2024-05-06 12:15:57 浏览: 18
对于图片形式的数据集,可以使用Python中的sklearn库中的train_test_split方法进行随机划分。具体步骤如下:
1. 导入必要的库和模块:
```python
from sklearn.model_selection import train_test_split
import os
import shutil
import random
```
2. 定义数据集路径和训练集、测试集路径:
```python
data_dir = "path/to/data" # 数据集路径
train_dir = "path/to/train" # 训练集路径
test_dir = "path/to/test" # 测试集路径
```
3. 获取所有图片的路径:
```python
all_images = []
for root, dirs, files in os.walk(data_dir):
for file in files:
if file.endswith(".jpg"): # 只获取jpg格式的图片
all_images.append(os.path.join(root, file))
```
4. 随机打乱图片路径:
```python
random.shuffle(all_images)
```
5. 划分训练集和测试集:
```python
train_images, test_images = train_test_split(all_images, test_size=0.1, random_state=42)
```
6. 创建训练集和测试集文件夹,并将图片拷贝到对应文件夹:
```python
if not os.path.exists(train_dir):
os.makedirs(train_dir)
if not os.path.exists(test_dir):
os.makedirs(test_dir)
for image in train_images:
shutil.copy(image, train_dir)
for image in test_images:
shutil.copy(image, test_dir)
```
以上步骤中,train_test_split()方法的参数test_size设置为0.1,表示测试集占总数据集的10%。也可以根据需要调整这个比例。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)