Tensorflow 训练自己的数据集将数据直接导入到内存
作者:ruyiweicas 时间:2023-08-18 14:30:14
制作自己的训练集
下图是我们数据的存放格式,在data目录下有验证集与测试集分别对应iris_test, iris_train
为了向伟大的MNIST致敬,我们采用的数据名称格式和MNIST类似
classification_index.jpg
图像的index都是5的整数倍是因为我们选择测试集的原则是每5个样本,选择一个样本作为测试集,其余的作为训练集和验证集
生成这样数据的过程相对简单,如果有需要python代码的,可以给我发邮件,或者在我的github下载
至此,我们的训练集,测试集,验证集就生成成功了,之所以我们的文件夹只有训练集和测试集是因为我们在后续的训练过程中,会在训练集中分出一部分作为验证集,所以两者暂时合称为训练集
将数据集写入到Tensorflow中
1. 直接写入到队列中
import tensorflow as tf
import numpy as np
import os
train_dir = '/home/ruyiwei/data/iris_train/'#your data directory
def get_files(file_dir):
'''
Args:
file_dir: file directory
Returns:
list of images and labels
'''
iris = []
label_iris = []
contact = []
label_contact = []
for file in os.listdir(file_dir):
name = file.split('_')
if name[0]=="iris":
iris.append(file_dir + file)
label_iris.append(0)
else:
contact.append(file_dir + file)
label_contact.append(1)
print('There are %d iris\nThere are %d contact' %(len(iris), len(contact)))
image_list = np.hstack((iris, contact))
label_list = np.hstack((label_iris, label_contact))
temp = np.array([image_list, label_list])
temp = temp.transpose()
np.random.shuffle(temp)
image_list = list(temp[:, 0])
label_list = list(temp[:, 1])
label_list = [int(i) for i in label_list]
return image_list, label_list
为了大家更方便的理解和修改代码,我们对代码进行讲解如下
1-3行 : 导入需要的模块
5行: 定义训练集合的位置,这个需要根据自己的机器进行修改
7行: 定义函数 get_files
18行: os.listdir(file_dir) 获取指定目录file_dir下的所有文件名词,也就是我们的训练图片名称
18行:for file in os.listdir(file_dir): 遍历所有的图片
19行: name为一个数组,由于我们根据MINIST来定制的图片名词,所以file.split(‘_')会将图像名称分为两部分,第一部分为classification,通过name[0]来获得分类信息。
21行、24行:iris.append(file_dir + file)/contact.append(file_dir + file)将图像的绝对路径放入到iris/contact中
22行、25行:label_iris.append(0)/label_contact.append(1)给对应的图片贴标签
28-29行:将二分类的图像与标签压入到list中
31-33行:合并二分类图像,然后打乱
38行:返回打乱后对应的图像与标签
在spyder下执行如上代码后会返回如下信息
这样图像和标签信息就被load到了内存中,我们接下来就可以利用现有的模型对图像进行分类训练,模型的选择和训练的过程,我们会在后面进行讲解。
来源:https://blog.csdn.net/best_coder/article/details/70141075
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
MySQL 查询速度慢的原因
详解用selenium来下载小姐姐图片并保存
![](https://img.aspxhome.com/file/2023/8/109588_0s.png)
python如何制作英文字典
IA学习笔记02:组织体系
![](https://img.aspxhome.com/file/UploadPic/20096/12/e6b798e5ae9de7bd91-e6b798efbc81e68891e5969ce6aca2-e589afe69cac-95s.jpg)
Python astype(np.float)函数使用方法解析
![](https://img.aspxhome.com/file/2023/5/83905_0s.png)
Pytorch神经网络参数管理方法详细讲解
Windows下nodejs安装及环境配置的实战步骤
![](https://img.aspxhome.com/file/2023/9/129499_0s.png)
简单的MySQL备份与还原方法分享
PHP+redis实现添加处理投票的方法
基于Python制作一键桌面整理工具
![](https://img.aspxhome.com/file/2023/1/131281_0s.jpg)
js中Array.forEach跳出循环的方法实例
![](https://img.aspxhome.com/file/2023/2/126172_0s.png)
Python爬虫模拟登录带验证码网站
![](https://img.aspxhome.com/file/2023/6/107796_0s.png)
浅谈MySQL event 计划任务
使用ASP实现广告代理
详解Python中Sync与Async执行速度快慢对比
![](https://img.aspxhome.com/file/2023/8/92138_0s.png)
Oracle 数据表分区的策略
python中可以声明变量类型吗
Python3 使用pip安装git并获取Yahoo金融数据的操作
![](https://img.aspxhome.com/file/2023/1/63941_0s.jpg)