Pytorch基础入门
Pytorch介紹
Torch是一個(gè)開源的機(jī)器學(xué)習(xí)的框架,早在2002年就發(fā)布了Torch的初版, Torch的編程語言為C和Lua。如今的Torch7依舊是熱門的深度學(xué)習(xí)框架之一。
PyTorch是在2017年1月由Facebook推出的。它是經(jīng)典機(jī)器學(xué)習(xí)庫Torch框架的一個(gè)端口,主要編程語言為python.
Torch: 2002年發(fā)布,早期的機(jī)器學(xué)習(xí)框架。
Theano: 2008年開發(fā),第一個(gè)影響力較大的python深度學(xué)習(xí)框架。
CNTK:2016年1月由微軟公司開源,在語音領(lǐng)域效果比較突出。
TensorFlow:2015年11月Google開源,目前最熱門深度學(xué)習(xí)框架之一。
Keras: 以Theano/Tensorflow/CNTK作為底層,最容易使用的深度學(xué)習(xí)框架。
Caffe/Caffe2:2013年開源的C++深度學(xué)習(xí)框架,曾經(jīng)計(jì)算機(jī)視覺領(lǐng)域的王者。
MXNet: 2015年發(fā)布,AWS云計(jì)算的官方深度學(xué)習(xí)平臺(tái)。
Paddle: 2016年8月開源的百度深度學(xué)習(xí)框架。
PyTorch: 2017年開源,Torch的python版本,目前最有潛力,最熱門的深度學(xué) 習(xí)框架之一。
Pytorch安裝
https://pytorch.org/打開Pytorch官網(wǎng)進(jìn)行下載,
根據(jù)自己電腦選擇相應(yīng)的選項(xiàng),最后把下方的指令輸入CMD中執(zhí)行即可。
MNIST數(shù)據(jù)集介紹
數(shù)據(jù)集被分成兩部分: 60000行的訓(xùn)練數(shù)據(jù)集( mnist.train)和10000行的測試數(shù)據(jù)集( mnist.test)
一張圖片包含28* 28個(gè)像素,我們把這一個(gè)數(shù)組展開成一個(gè)向量,長度是28* 28=784。如果把數(shù)據(jù)用矩陣表示,可以把MNIST訓(xùn)練數(shù)據(jù)變成一個(gè)形狀為 [60000, 784] 的矩陣,第一個(gè)維度數(shù)字用來索引圖片,第二個(gè)維度數(shù)字用來索引每張圖片中的像素點(diǎn)。圖片里的某個(gè)像素的強(qiáng)度值介于0-1之間。
One-hot編碼
MNIST數(shù)據(jù)集的標(biāo)簽是介于0-9的數(shù)字,我們要把標(biāo)簽轉(zhuǎn)化為“one-hotvectors” 。一個(gè)one-hot向量除了某一位數(shù)字是1以外,其余維度數(shù)字都是0,比如標(biāo)簽0將表示為([1,0,0,0,0,0,0,0,0,0]),標(biāo)簽3將表示為
([0,0,0,1,0,0,0,0,0,0])
Softmax函數(shù)介紹
在多分類問題中,我們通常會(huì)使用softmax函數(shù)作為網(wǎng)絡(luò)輸出層的激活函數(shù),softmax函數(shù)可以對輸出值進(jìn)行歸一化操作,把所有輸出值都轉(zhuǎn)化為概率,所有概率值加起來等于1, softmax的公式為:
損失函數(shù)
均方誤差(二次代價(jià)函數(shù))
激活函數(shù)的梯度f’(z)越大, w的大小調(diào)整得越快,訓(xùn)練收斂得就越快。激活函數(shù)的梯度f’(z)越小, w的大小調(diào)整得越慢,訓(xùn)練收斂得就越慢。
按理來說,如果損失函數(shù)越大,應(yīng)該進(jìn)行的求導(dǎo)越快,而二次代價(jià)函數(shù)做不到,引出交叉熵函數(shù)。
交叉熵
過擬合
防止過擬合
增大數(shù)據(jù)集
增大數(shù)據(jù)集方法:
Early stopping
在訓(xùn)練模型的時(shí)候,我們往往會(huì)設(shè)置一個(gè)比較大的迭代次數(shù)。 Earlystopping便是一種提前結(jié)束訓(xùn)練的策略用來防止過擬合。
一般的做法是記錄到目前為止最好的validation accuracy,當(dāng)連續(xù)10個(gè)Epoch沒有達(dá)到最佳a(bǔ)ccuracy時(shí),則可以認(rèn)為accuracy不再提高了。此時(shí)便可以停止迭代了( Early Stopping)。
Dropout
在訓(xùn)練數(shù)據(jù)集的時(shí)候,隨機(jī)的屏蔽掉一些神經(jīng)元,以提高數(shù)據(jù)的魯棒性
正則化項(xiàng)
優(yōu)化器
Adadelta
Adagrad
Adam 一般使用Adam
Adamax
AdamW
ASGD
LBFGS
RMSprop
Rprop
SGD
SparseAdam
卷積神經(jīng)網(wǎng)絡(luò)CNN
卷積神經(jīng)網(wǎng)絡(luò)是近年發(fā)展起來,并廣泛應(yīng)用于圖像處理, NLP等領(lǐng)域的一種多層神經(jīng)網(wǎng)絡(luò)。
局部感受野
權(quán)值共享
卷積計(jì)算
池化
Padding
SAME PADDING:
給平面外部補(bǔ)0
卷積窗口采樣后得到一個(gè)跟原來大小相同的平面
VALID PADDING:
不會(huì)超出平面外部
卷積窗口采樣后得到一個(gè)比原來平面小的平面
貓狗分類案例
訓(xùn)練模型
import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable from torchvision import datasets, transforms, models from torch.utils.data import DataLoader from torchvision.models import VGG16_Weights# 數(shù)據(jù)預(yù)處理 transform = transforms.Compose([transforms.RandomResizedCrop(224), # 對圖形進(jìn)行切割后,在形成固定大小transforms.RandomRotation(20), # 隨機(jī)角度進(jìn)行旋轉(zhuǎn)transforms.RandomHorizontalFlip(p=0.5), # 隨機(jī)水平移動(dòng)transforms.ToTensor() # 轉(zhuǎn)成pytorch使用的tensor數(shù)據(jù)集形式 ])# 讀取數(shù)據(jù) root = 'image' train_dataset = datasets.ImageFolder(root + '/train', transform) test_dataset = datasets.ImageFolder(root + '/test', transform)# 導(dǎo)入數(shù)據(jù) train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=8, shuffle=True) test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=8, shuffle=True)# classes = train_dataset.classes classes_index = train_dataset.class_to_idxbatch_size = 64 LR = 0.0001 model = models.vgg16(weights=VGG16_Weights.DEFAULT) # model = model.cuda()# 只訓(xùn)練全連接層 for param in model.parameters():param.requires_grad = False # 構(gòu)建新的全連接層 model.classifier = torch.nn.Sequential(torch.nn.Linear(25088, 100),torch.nn.ReLU(),torch.nn.Dropout(p=0.5),torch.nn.Linear(100, 2)) # 定義損失函數(shù) mse_loss = nn.CrossEntropyLoss() # 定義優(yōu)化器 optimizer = optim.SGD(model.parameters(), LR, momentum=0.9)def train():model.train()for i, data in enumerate(train_loader):# 獲得一個(gè)批次的數(shù)據(jù)和標(biāo)簽inputs, labels = data# inputs = Variable(inputs.cuda())# labels = Variable(labels.cuda())# 獲得模型預(yù)測結(jié)果(64,10)out = model(inputs)# to onehot,把數(shù)據(jù)標(biāo)簽變成獨(dú)熱編碼# (64)-(64,1)loss = mse_loss(out, labels)# 梯度清0optimizer.zero_grad()# 計(jì)算梯度loss.backward()# 修改權(quán)值optimizer.step()def test():model.eval()correct = 0for i, data in enumerate(test_loader):# 獲得一個(gè)批次的數(shù)據(jù)和標(biāo)簽inputs, labels = data# inputs = Variable(inputs.cuda())# labels = Variable(labels.cuda())# 獲得模型預(yù)測結(jié)果(64,10)out = model(inputs)# 獲得最大值,以及最大值所在的位置_, predicted = torch.max(out, 1)# 預(yù)測正確的數(shù)量correct += (predicted == labels).sum()print("Test acc:{0}".format(correct.item() / len(test_dataset)))correct = 0for i, data in enumerate(train_loader):# 獲得一個(gè)批次的數(shù)據(jù)和標(biāo)簽inputs, labels = data# inputs = Variable(inputs.cuda())# labels = Variable(labels.cuda())# 獲得模型預(yù)測結(jié)果(64,10)out = model(inputs)# 獲得最大值,以及最大值所在的位置_, predicted = torch.max(out, 1)# 預(yù)測正確的數(shù)量correct += (predicted == labels).sum()print("Train acc:{0}".format(correct.item() / len(train_dataset)))for epoch in range(2):print('epoch:', epoch)train()test() torch.save(model.state_dict(), 'cat_dog_cnn.pth')測試模型
import numpy as np import torch import torch.nn as nn import torch.optim as optim from PIL import Image from torch.autograd import Variable from torchvision import datasets, transforms, models from torch.utils.data import DataLoader from torchvision.models import VGG16_Weightsmodel = models.vgg16(weights=VGG16_Weights.DEFAULT) # 構(gòu)建新的全連接層 model.classifier = torch.nn.Sequential(torch.nn.Linear(25088, 100),torch.nn.ReLU(),torch.nn.Dropout(p=0.5),torch.nn.Linear(100, 2))model.load_state_dict(torch.load('cat_dog_cnn.pth'))model.eval()label = np.array(['cat', 'dog'])# 數(shù)據(jù)預(yù)處理 transform = transforms.Compose([transforms.Resize(224),transforms.ToTensor() ])def predict(image_path):# 打開圖片img = Image.open(image_path)# 數(shù)據(jù)處理,再增加一個(gè)維度img = transform(img).unsqueeze(0)# img = img.convert("RGB")# 預(yù)測得到結(jié)果outputs = model(img)# 獲得最大值所在位置_, predicted = torch.max(outputs, 1)# 轉(zhuǎn)化為類別名稱print(label[predicted.item()])predict('image/test/cat/cat.1120.jpg')轉(zhuǎn)載自bilibili覃秉豐
總結(jié)
以上是生活随笔為你收集整理的Pytorch基础入门的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 东华大学 oj87——弟弟的作业
- 下一篇: Lin总线概述及入门