在pytorch中我么如何去学着搭建一个最基本的架构呢?
一个架构的搭建分为一下几步:
1:导入常用的包:torch,torch.nn,torch.functional等
2:将要处理的数据导入,这里不得不说,pytorch现阶段支持的数据集比较少,如果你要使用的数据集不在其支持的数据集列表里,那你就要自己编写程序进行导入了,这个会在后面的章节里详说
3:网络的搭建,写一个网络类,然后内部包含两个方法:
1》__init__()函数,这个主要是完成搭建材料的导入工作,如:self.relu = torch.nn.Relu()
2》forward()函数,这个主要是按照顺序搭建起整个网络来,最后得到结果
4:选择要使用的损失函数类型和优化器类型
5:框架最便利也是最吸引人的自动求导
1》zero_grad():将所有的参数的导数置零(为什么要置零?本人亲身试验过,如果不置零,其参数的导数会不断的累加,我们知道,我们在进行梯度下降的过程中当前的下降只用到当前的导数,下一个地点的下降是下个地点导数的事情,如果将其累加,就会出错)
2》losses.backward()这里的losses是我们使用的损失函数,对其进行反向求导
3》optim.step()这里的optim是我们选择的优化器,step是进行一步优化,也就是将我们上面backward求导后的各个参数进行梯度下降一次,也即是做了一次优化。
下面贴出一个最基本的程序:
import torch
from torch import nn, optim
import torch.nn.functional as F
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision import datasets
import time
# 定义超参数
batch_size = 32
learning_rate = 1e-3
num_epoches = 10
# 下载训练集 MNIST 手写数字训练集
train_dataset = datasets.MNIST(
root='./data', train=True, transform=transforms.ToTensor(), download=True)
test_dataset = datasets.MNIST(
root='./data', train=False, transform=transforms.ToTensor())
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
# 定义 Logistic Regression 模型
class Logstic_Regression(nn.Module):
def __init__(self, in_dim, n_class):
super(Logstic_Regression, self).__init__()
self.logstic = nn.Linear(in_dim, n_class)
def forward(self, x):
out = self.logstic(x)
return out
model = Logstic_Regression(28 * 28, 10) # 图片大小是28x28
use_gpu = torch.cuda.is_available() # 判断是否有GPU加速
if use_gpu:
model = model.cuda()
# 定义loss和optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=learning_rate)
# 开始训练
for epoch in range(num_epoches):
print('*' * 10)
print('epoch {}'.format(epoch + 1))
since = time.time()
running_loss = 0.0
running_acc = 0.0
for i, data in enumerate(train_loader, 1):
img, label = data
img = img.view(img.size(0), -1) # 将图片展开成 28x28
if use_gpu:
img = Variable(img).cuda()
label = Variable(label).cuda()
else:
img = Variable(img)
label = Variable(label)
# 向前传播
out = model(img)
loss = criterion(out, label)
running_loss += loss.data[0] * label.size(0)
print('label.size={},loss.data[0]={}'.format(label.size(0),loss.data[0]))
_, pred = torch.max(out, 1)
num_correct = (pred == label).sum()
running_acc += num_correct.data[0]
# 向后传播
optimizer.zero_grad()
loss.backward()
optimizer.step()#更新所有的参数
if i % 300 == 0:
print('[{}/{}] Loss: {:.6f}, Acc: {:.6f}'.format(
epoch + 1, num_epoches, running_loss / (batch_size * i),
running_acc / (batch_size * i)))
print('Finish {} epoch, Loss: {:.6f}, Acc: {:.6f}'.format(
epoch + 1, running_loss / (len(train_dataset)), running_acc / (len(
train_dataset))))
model.eval()
eval_loss = 0.
eval_acc = 0.
for data in test_loader:
img, label = data
img = img.view(img.size(0), -1)
if use_gpu:
img = Variable(img, volatile=True).cuda()
label = Variable(label, volatile=True).cuda()
else:
img = Variable(img, volatile=True)
label = Variable(label, volatile=True)
out = model(img)
loss = criterion(out, label)
eval_loss += loss.data[0] * label.size(0)
_, pred = torch.max(out, 1)
num_correct = (pred == label).sum()
eval_acc += num_correct.data[0]
print('Test Loss: {:.6f}, Acc: {:.6f}'.format(eval_loss / (len(
test_dataset)), eval_acc / (len(test_dataset))))
print('Time:{:.1f} s'.format(time.time() - since))
print()
# 保存模型
torch.save(model.state_dict(), './logstic.pth')