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文件的数据,前面表示图片的路径,后面表示图片的标签。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您提供代码实现。在这里,我将使用Keras中的ResNet50预训练模型,并使用Fashion-MNIST数据集对十种服装进行分类。首先,我们需要安装一些必要的库: ``` !pip install tensorflow !pip install keras !pip install matplotlib ``` 接下来,我们将加载数据集并进行预处理: ```python import numpy as np import keras from keras.datasets import fashion_mnist from keras.preprocessing.image import ImageDataGenerator # 数据集路径 (x_train, y_train), (x_test, y_test) = fashion_mnist.load_data() # 将图像转换为RGB格式 x_train = np.repeat(x_train[..., np.newaxis], 3, -1) x_test = np.repeat(x_test[..., np.newaxis], 3, -1) # 批量大小 batch_size = 32 # 数据增强 train_datagen = ImageDataGenerator( rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) # 没有数据增强的验证数据生成器 val_datagen = ImageDataGenerator(rescale=1./255) # 训练集生成器 train_generator = train_datagen.flow( x_train, keras.utils.to_categorical(y_train), batch_size=batch_size) # 验证集生成器 val_generator = val_datagen.flow( x_test, keras.utils.to_categorical(y_test), batch_size=batch_size) ``` 接下来,我们将加载ResNet50模型,并对其进行微调,以适应我们的数据集: ```python from keras.applications.resnet50 import ResNet50 from keras.layers import Dense, GlobalAveragePooling2D from keras.models import Model # 加载ResNet50模型,不包括顶层(全连接层) base_model = ResNet50(weights='imagenet', include_top=False) # 添加全局平均池化层 x = base_model.output x = GlobalAveragePooling2D()(x) # 添加全连接层,输出为十个类别 predictions = Dense(10, activation='softmax')(x) # 构建我们需要训练的完整模型 model = Model(inputs=base_model.input, outputs=predictions) # 冻结ResNet50的所有层,以便在训练过程中不更新它们的权重 for layer in base_model.layers: layer.trainable = False ``` 现在,我们可以开始训练模型了: ```python from keras.optimizers import SGD # 编译模型,指定损失函数、优化器和评价指标 model.compile(loss='categorical_crossentropy', optimizer=SGD(lr=0.001), metrics=['accuracy']) # 训练模型 history = model.fit_generator( train_generator, steps_per_epoch=x_train.shape[0] // batch_size, epochs=10, validation_data=val_generator, validation_steps=x_test.shape[0] // batch_size) ``` 最后,我们可以使用matplotlib库绘制训练和验证的准确率和损失曲线: ```python import matplotlib.pyplot as plt # 绘制训练和验证的准确率曲线 plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Train', 'Val'], loc='upper left') plt.show() # 绘制训练和验证的损失曲线 plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model loss') plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['Train', 'Val'], loc='upper left') plt.show() ``` 现在您应该可以使用这些代码实现您的需求了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值