Resnet for Fashion_Mnist(一)
目录
写作目的
通过使用resnet 实现 Fashion_Mnist,学会使用pytorch框架。这系列博客全方位介绍了如何使用pytorch,包括数据制作、模型定义、模型训练及验证,模型保存、模型加载、测试集预测。
Fashion_Mnist
Fashion_Mnist是包含十类服装的图片数据集,其实就是Mnist手写字体集的加强版,但是想提高在Fashion_Mnist的准确率却不像Mnist那么容易。因此,我们需要使用高级的神经网络去训练,达到较高的准确率。
关于Fashion_Mnist的详细介绍,参考 https://github.com/zalandoresearch/fashion-mnist
下面,我们开始详细介绍如何在pytorch上使用resnet 实现 Fashion_Mnist。
制作数据集
制作数据集的目的是让自己的数据符合pytorch上的规范。简单来说,就是符合下面这个函数需要的dataset。
torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=False, num_workers=0)
我以csv文件为例进行说明。首先展示下面一段代码:
# -*- coding: utf-8 -*-
# 制作pytorch要求的数据格式
import numpy as np
import csv
import matplotlib.pyplot as pyplot
csv_path = 'E:/data/fashion_train.csv'
save_path = 'train_data/'
txt_path = 'train.txt'
w = 28
h = 28
# 将csv文件的像素转为图像,并用一个txt文件保存标签和图像的路径
def read_csv_img(path):
csv_file = open(path)
csv_file_reader_lines = csv.reader(csv_file)
txt_file = open(txt_path, 'w')
count = 0
for csv_row in csv_file_reader_lines:
count = count + 1
data_row = np.float32(csv_row[1:])
img = np.array(data_row).reshape(w, h)
pyplot.imshow(img)
name = save_path + '%05d.jpg' % count
label = csv_row[0]
txt_file.write(name + '\t' + label + '\n')
pyplot.imsave(name, img)
read_csv_img(csv_path)
上面代码的意思是,遍历csv文件的每一行,将第一列的到最后一列的值存到data_row 中,然后reshape成28*28的矩阵,生成图像,保存到指定路径中,将路径的名字保存到name中。将第一列中的值保存到label中。最后,生成txt文件,txt文件的每一行是一张图片的路径和标签。至此,数据准备完成。
下面,展示生成的txt文件:
写Datasets函数
由于torchvision.datasets()
没法直接使用我们自己的数据,需要我们自己写Datasets函数,继承Dataset
类。代码如下:
from torch.utils.data import Dataset
from PIL import Image
# -----------------ready the dataset--------------------------
class MyDataset(Dataset):
def __init__(self, root, datatxt, transform=None, target_transform=None):
fh = open(root + datatxt, 'r')
imgs = []
for line in fh:
line = line.strip('\n')
line = line.rstrip()
words = line.split()
imgs.append((words[0], int(words[1])))
self.root = root
self.imgs = imgs
self.transform = transform
self.target_transform = target_transform
def __getitem__(self, index):
fn, label = self.imgs[index]
#img = Image.open(root + fn).convert('RGB')
img = Image.open(self.root + fn).convert('L')
if self.transform is not None:
img = self.transform(img)
return img, label
def __len__(self):
return len(self.imgs)
上面的代码简单易懂,就不详细解释了。其中,words[0], words[1]
就是表示我们之前制作的txt文件的数据,前面表示图片的路径,后面表示图片的标签。