2019-04-03/04 Pytorch:mnist訓練預訓練模型

參考鏈接:1.pytorch下搭建網(wǎng)絡訓練并保存模型 - sjtuxx_lee的博客 - CSDN博客

? ? ? ? ? ? ? ? ? 2.詳解 MNIST 數(shù)據(jù)集 - 閑漢 - 博客園

? ? ? ? ? ? ? ? ? 3.image — Matplotlib 3.0.3 documentation

? ? ? ? ? ? ? ? ? 4.torchvision庫簡介 - DrHW - 博客園

? ? ? ? ? ? ? ? ? 5.pytorch方法測試——損失函數(shù)(CrossEntropyLoss) - tmk_01的博客 - CSDN博客


加載并保存圖像信息

首先下載mnist的數(shù)據(jù)集:官網(wǎng)的那個可能被墻了,貼上網(wǎng)盤鏈接,提取碼: r2k7


按照規(guī)定建立好文件夾以及子文件夾。

修改相應代碼(兩部分):

1.更改root_path,我的是root_path = 'E:/data_JH/pytorch/mnist/'

?? 增加mnist.npz的地址,為了以后的本地導入,

?? path = 'E:/data_JH/pytorch/mnist/mnist.npz'


2.更改成本地導入,改動點如下

def LoadData(root_path, base_path, training_path, test_path):

? ? ##############本地下載版本##############

? ? f = np.load(path)

? ? x_train, y_train = f['x_train'], f['y_train']

? ? x_test, y_test = f['x_test'], f['y_test']

? ? f.close()

? ? #######################################

? ? #(x_train, y_train), (x_test, y_test) = mnist.load_data() 在線下載版本



遇到的問題以及解決方案:

1.matplotlib沒有image這個模塊(module ‘matplotlib’ has no attribute 'image' )

查找了matplotlib官方文件庫[3],發(fā)現(xiàn)是有matplotlib.image.imsave這個命令的,但是他的版本是Version3.0.3,我的版本是Version2.0.2。推測是安裝這個包沒安全面,打開Anaconda Navigator,搜索matplotlib,把相關(guān)的包都點擊Apply。


定義自己的DATASET

pytorch訓練數(shù)據(jù)時需要數(shù)據(jù)集為Dataset類,便于迭代等等,這里將加載保存之后的數(shù)據(jù)封裝成Dataset類,分別為:

1.繼承該類需要寫初始化方法(__init__)

2.獲取指定下標數(shù)據(jù)的方法(__getitem__)

3.獲取數(shù)據(jù)個數(shù)的方法(__len__)。

尤其需要注意的是要把label轉(zhuǎn)為LongTensor類型的。


用mnist訓練網(wǎng)絡

前期準備工作:

1.把DataProcessingMnist類和BuildAlexNet類文件分別命名成DataProcessing和BuildModel,否則導入的時候會出現(xiàn)問題。

2.root_path,model_path改成你文件的位置

3.把代碼中的.data[0]改成item()


訓練中。。。

訓練完成


下面是修改后的訓練代碼以及我的理解,原版在參考鏈接1里面。


import torch

import os

from torchvision import transforms ? ? ? ? ?? #圖像變換包,具體見[4]

import torch.optim as optim ? ? ? ? ? ? ? ? ? ? ? #優(yōu)化算法包

from torch.autograd import Variable

from torch.utils.data import DataLoader

import DataProcessing as DP

import BuildModel as BM

import torch.nn as nn

if __name__ == '__main__':

? ? os.environ['CUDA_VISIBLE_DEVICES'] = '0,1' #設置系統(tǒng)環(huán)境變量

? ? root_path = 'E:/data_JH/pytorch/mnist/' ? ? ??

? ? training_path = 'trainingset/'

? ? test_path = 'testset/'

? ? model_path = 'E:/data_JH/pytorch/mnist/model/'


? ? training_imgfile = training_path + 'trainingset_img.txt'

? ? training_labelfile = training_path + 'trainingset_label.txt'

? ? training_imgdata = training_path + 'img/'


? ? test_imgfile = test_path + 'testset_img.txt'

? ? test_labelfile = test_path + 'testset_label.txt'

? ? test_imgdata = test_path + 'img/'


? ? #parameter

? ? batch_size = 128

? ? epochs = 20

? ? model_type = 'pre'

? ? nclasses = 10 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #最終分類數(shù)目

? ? lr = 0.01 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?? #梯度下降率

? ? use_gpu = torch.cuda.is_available()


? ? transformations = transforms.Compose( ? ? ? ? ? ? ?? #定義組合變換

? ? ? ? ? ? [transforms.Scale(256), ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??

? ? ? ? ? ? transforms.CenterCrop(224),

? ? ? ? ? ? transforms.ToTensor(),

? ? ? ? ? ? transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225])

? ? ? ? ? ? ? ? ? ? ])


? ? dataset_train = DP.DataProcessingMnist(root_path, training_imgfile, training_labelfile, training_imgdata, transformations)

? ? dataset_test = DP.DataProcessingMnist(root_path, test_imgfile, test_labelfile, test_imgdata, transformations)


? ? num_train, num_test = len(dataset_train), len(dataset_test)


? ? train_loader = DataLoader(dataset_train, batch_size = batch_size, shuffle = True, num_workers = 0)

? ? test_loader = DataLoader(dataset_test, batch_size = batch_size, shuffle = False, num_workers = 0)


? ? # build model

? ? model = BM.BuildAlexNet(model_type, nclasses)

? ? optimizer = optim.SGD(model.parameters(), lr = lr)

? ? criterion = nn.CrossEntropyLoss() ? ? ? ? ? ? ? ? ?? #損失函數(shù),詳見[5]


? ? for epoch in range(epochs):

? ? ? ? epoch_loss = 0

? ? ? ? correct_num = 0

? ? ? ? for i, traindata in enumerate(train_loader):

? ? ? ? ? ? x_train, y_train = traindata

? ? ? ? ? ? if use_gpu:

? ? ? ? ? ? ? ? x_train, y_train = Variable(x_train.cuda()),Variable(y_train.cuda())

? ? ? ? ? ? ? ? model = model.cuda()

? ? ? ? ? ? else:

? ? ? ? ? ? ? ? x_train, y_train = Variable(x_train),Variable(y_train)

? ? ? ? ? ? y_pre = model(x_train)

? ? ? ? ? ? _, label_pre = torch.max(y_pre.data, 1)

? ? ? ? ? ? if use_gpu:

? ? ? ? ? ? ? ? y_pre = y_pre.cuda()

? ? ? ? ? ? ? ? label_pre = label_pre.cuda()

? ? ? ? ? ? model.zero_grad()

? ? ? ? ? ? loss = criterion(y_pre, y_train)

? ? ? ? ? ? loss.backward()

? ? ? ? ? ? optimizer.step()

? ? ? ? ? ? epoch_loss += loss.item()

? ? ? ? ? ? correct_num += torch.sum(label_pre == y_train.data)? ? ? ?

? ? ? ? ? ? acc = (torch.sum(label_pre == y_train.data).float()/len(y_train))?

? ? ? ? ? ? print('batch loss: {} batch acc: {}'.format(loss.item(),acc.item()))

? ? ? ? print('epoch: {} training loss: {}, training acc: {}'.format(epoch, epoch_loss, correct_num.float()/num_train))

? ? ? ? if (epoch+1) % 5 ==0:

? ? ? ? ? ? test_loss = 0

? ? ? ? ? ? test_acc_num = 0

? ? ? ? ? ? for j, testdata in enumerate(test_loader):

? ? ? ? ? ? ? ? x_test, y_test = testdata

? ? ? ? ? ? ? ? if use_gpu:

? ? ? ? ? ? ? ? ? ? x_test, y_test = Variable(x_test.cuda()), Variable(y_test.cuda())

? ? ? ? ? ? ? ? else:

? ? ? ? ? ? ? ? ? ? x_test, y_test = Variable(x_test), Variable(y_test)

? ? ? ? ? ? ? ? y_pre = model(x_test)

? ? ? ? ? ? ? ? _, label_pre = torch.max(y_pre.data, 1)

? ? ? ? ? ? ? ? loss = criterion(y_pre, y_test)

? ? ? ? ? ? ? ? test_loss += loss.item()

? ? ? ? ? ? ? ? test_acc_num += torch.sum(label_pre == y_test.data)

? ? ? ? ? ? print('epoch: {} test loss: {} test acc: {}'.format(epoch, test_loss, test_acc_num.float()/num_test))

? ? torch.save(model.state_dict(), model_path + 'AlexNet_params.pkl')


PS:哼,我學會在簡書里面用那種代碼的排版了。下一篇就用?。?a target="_blank" rel="nofollow">簡書怎么添加并且顯示代碼_百度經(jīng)驗)

待解決:訓練原理還搞得不是太清楚。鏈接5記得有時間搞透徹



最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容