使用DataSet数据集类,我们可以自己定义一个类,并继承DataSet类,同时实现**getitem()**方法。
根据官方文档描述,所有的subclass都应该继承Dataset类。其中__getitem__方法是必须覆盖的。这个方法的作用是获取数据集中的某个数据。
而我们可以通过构造方法__init__来初始化我们的数据集。
我们也可以选择性的决定是否要使用__len__方法来实现我们的数据集类。
因此,对于我们如下图所示的目录中 ,
我们的train目录下存在一个ants的数据集,这个ants就是我们所要给这个集合打的标签。
那么,我们对于数据集类的方法能够这样使用。
class MyData(Dataset):
def __init__(self,root_dir,label_dir):
self.root_dir = root_dir;
self.label_dir = label_dir;
self.path = os.path.join(self.root_dir,self.label_dir);
self.img_path_list = os.listdir(self.path)
def __getitem__(self,idx):
img_name = self.img_path_list[idx];
img_path = os.path.join(self.root_dir,self.label_dir,img_name)
img = Image.open(img_path)
label = self.label_dir
return img,label
def __len__(self):
return len(self.img_path_list)
其中,构造函数初始化了我们的文件目录,获取了所有图片资源的路径,并使用getitem方法来返回单个图片资源,这里的图片资源是PIL类型的。
在后期我们可以使用TensorBoard来进一步分析我们的数据。