本人學(xué)習(xí)pytorch主要參考官方文檔和 莫煩Python中的pytorch視頻教程置吓。
后文主要是對pytorch官網(wǎng)的文檔的總結(jié)肤舞。
主要用torch.nn
模型和forward(imput)
煤墙。
網(wǎng)絡(luò)構(gòu)建代碼:
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# kernel
self.conv1 = nn.Conv2d(1, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
# an affine operation: y = Wx + b
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
#改變數(shù)據(jù)維度為一維
x = x.view(-1, self.num_flat_features(x))
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
def num_flat_features(self, x):
size = x.size()[1:] # all dimensions except the batch dimension
num_features = 1
for s in size:
num_features *= s
return num_features
net = Net()
print(net)
#輸出
# Net(
# (conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))
# (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
# (fc1): Linear(in_features=400, out_features=120, bias=True)
# (fc2): Linear(in_features=120, out_features=84, bias=True)
# (fc3): Linear(in_features=84, out_features=10, bias=True)
# )
參數(shù)說明:
#獲取網(wǎng)絡(luò)中的所有參數(shù)的列表
params = list(net.parameters())
#獲取網(wǎng)絡(luò)參數(shù)長度
print(len(params))
#獲取 conv1的weight矩陣大小
print(params[0].size())
之后以莫凡pytorch中的代碼為例進(jìn)行說明记盒。
import os
# third-party library
import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision
import matplotlib.pyplot as plt
# 設(shè)置網(wǎng)絡(luò)超參數(shù)
EPOCH = 1 # 左右的數(shù)據(jù)總共迭代幾次
BATCH_SIZE = 50
LR = 0.001 # 學(xué)習(xí)率
DOWNLOAD_MNIST = False #是否下載MNIST數(shù)據(jù)集合
# 檢測數(shù)據(jù)集是否存在
if not(os.path.exists('./mnist/')) or not os.listdir('./mnist/'):
# not mnist dir or mnist is empyt dir
DOWNLOAD_MNIST = True
train_data = torchvision.datasets.MNIST(
root='./mnist/', train=True, #提取訓(xùn)練數(shù)據(jù)集
# 將PIL圖像或者numpy.ndarry轉(zhuǎn)化為torch.FloatTensor掷豺,維度為(C x H x W),并歸一化為 [0.0, 1.0]
transform=torchvision.transforms.ToTensor(),
download=DOWNLOAD_MNIST,
)
# 繪制一個圖像
# print(train_data.train_data.size()) # (60000, 28, 28)
# print(train_data.train_labels.size()) # (60000)
# plt.imshow(train_data.train_data[0].numpy(), cmap='gray')
# plt.title('%i' % train_data.train_labels[0])
# plt.show()
# 啟動數(shù)據(jù)加載器龄毡,在加載數(shù)據(jù)時進(jìn)行打亂順序想诅,批次為BATCH_SIZE召庞。批次數(shù)據(jù)的維度為(50, 1, 28, 28)
train_loader = Data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)
# 取2000個測試圖像及對應(yīng)標(biāo)簽進(jìn)行測試
test_data = torchvision.datasets.MNIST(root='./mnist/', train=False)
# 數(shù)據(jù)進(jìn)行歸一化為(0,1)
test_x = torch.unsqueeze(test_data.test_data, dim=1).type(torch.FloatTensor)[:2000]/255.
test_y = test_data.test_labels[:2000]
# 定義網(wǎng)絡(luò)結(jié)構(gòu)
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Sequential( # input shape (1, 28, 28)
nn.Conv2d(
in_channels=1, # input height
out_channels=16, # n_filters
kernel_size=5, # filter size
stride=1, # filter movement/step
padding=2, # if want same width and length of this image after Conv2d, padding=(kernel_size-1)/2 if stride=1
), # output shape (16, 28, 28)
nn.ReLU(), # activation
nn.MaxPool2d(kernel_size=2), # choose max value in 2x2 area, output shape (16, 14, 14)
)
self.conv2 = nn.Sequential( # input shape (16, 14, 14)
nn.Conv2d(16, 32, 5, 1, 2), # output shape (32, 14, 14)
nn.ReLU(), # activation
nn.MaxPool2d(2), # output shape (32, 7, 7)
)
self.out = nn.Linear(32 * 7 * 7, 10) # fully connected layer, output 10 classes
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = x.view(x.size(0), -1) # flatten the output of conv2 to (batch_size, 32 * 7 * 7)
output = self.out(x)
return output, x # return x for visualization
cnn = CNN()
# 打印網(wǎng)絡(luò)結(jié)構(gòu)
print(cnn)
# 定義網(wǎng)絡(luò)優(yōu)化方法岛心、損失*必須在訓(xùn)練循環(huán)外定義
optimizer = torch.optim.Adam(cnn.parameters(), lr=LR) # optimize all cnn parameters
loss_func = nn.CrossEntropyLoss() # the target label is not one-hotted
# 可視化代碼
from matplotlib import cm
try: from sklearn.manifold import TSNE; HAS_SK = True
except: HAS_SK = False; print('Please install sklearn for layer visualization')
def plot_with_labels(lowDWeights, labels):
plt.cla()
X, Y = lowDWeights[:, 0], lowDWeights[:, 1]
for x, y, s in zip(X, Y, labels):
c = cm.rainbow(int(255 * s / 9)); plt.text(x, y, s, backgroundcolor=c, fontsize=9)
plt.xlim(X.min(), X.max()); plt.ylim(Y.min(), Y.max()); plt.title('Visualize last layer'); plt.show(); plt.pause(0.01)
plt.ion()
# 訓(xùn)練和測試
for epoch in range(EPOCH):
# 獲取訓(xùn)練圖像及標(biāo)簽
for step, (b_x, b_y) in enumerate(train_loader): # gives batch data, normalize x when iterate train_loader
# 獲取輸出結(jié)果
output = cnn(b_x)[0]
# 獲取損失
loss = loss_func(output, b_y)
# 清理訓(xùn)練階段梯度
optimizer.zero_grad()
# 反向傳播,計算梯度
loss.backward()
# 執(zhí)行梯度操作
optimizer.step()
# 每迭代50個batch進(jìn)行一次測試并繪圖
if step % 50 == 0:
test_output, last_layer = cnn(test_x)
pred_y = torch.max(test_output, 1)[1].data.numpy()
accuracy = float((pred_y == test_y.data.numpy()).astype(int).sum()) / float(test_y.size(0))
print('Epoch: ', epoch, '| train loss: %.4f' % loss.data.numpy(), '| test accuracy: %.2f' % accuracy)
if HAS_SK:
# Visualization of trained flatten layer (T-SNE)
tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
plot_only = 500
low_dim_embs = tsne.fit_transform(last_layer.data.numpy()[:plot_only, :])
labels = test_y.numpy()[:plot_only]
plot_with_labels(low_dim_embs, labels)
plt.ioff()
# 進(jìn)行測試
test_output, _ = cnn(test_x[:10])
pred_y = torch.max(test_output, 1)[1].data.numpy()
print(pred_y, 'prediction number')
print(test_y[:10].numpy(), 'real number')
總體流程為篮灼。
1.定義網(wǎng)絡(luò)
2.設(shè)定優(yōu)化方法
3.確定損失
4.在訓(xùn)練中完成忘古,獲取結(jié)果,計算損失诅诱,清理損失髓堪、反傳、更新梯度娘荡。