步骤一 :安装 anaconda
超详细Anaconda安装教程_极小白的博客-CSDN博客
anaconda用处
Anaconda包括Conda、Python以及一大堆安装好的工具包,比如:numpy、pandas等,conda是一个开源的包、环境管理器,可以用于在同一个机器上安装不同版本的软件包及其依赖,并能够在不同的环境之间切换 (实质最主要的作用就是包的管理)
使用:
01=创建虚拟环境 conda create -n pytorch python=3.8
02=激活环境 activate pytorch)
步骤二:
安装pytorch PyTorch
选择cpu版本。及历史版本1.21.1 ,命令行:pip install torch==1.12.1+cpu torchvision==0.13.1+cpu torchaudio==0.12.1 --extra-index-url https://download.pytorch.org/whl/cpu
pytorch用处
PyTorch是一个开源的 Python 机器学习库,基于Torch,PyTorch是一个开源的深度学习框架,提供了各种张量操作并通过自动求导可以自动进行梯度计算,方便构建各种动态神经网络。支持使用GPU/TPU进行加速计算
步骤三:安装网络库 pandle
步骤四:训练素材
1.引入库
import torchvision
from torch.utils.tensorboard import SummaryWriter
from note9_LeNet import *
from torch import nn
from torch.utils.data import DataLoader
2.设置神经网络
import torch
from torch import nn
# 搭建神经网络
class Module(nn.Module):
def __init__(self):
super(Module, self).__init__()
self.model = nn.Sequential(
nn.Conv2d(3, 16, 5),
nn.MaxPool2d(2, 2),
nn.Conv2d(16, 32, 5),
nn.MaxPool2d(2, 2),
nn.Flatten(), # 注意一下,线性层需要进行展平处理
nn.Linear(32*5*5, 120),
nn.Linear(120, 84),
nn.Linear(84, 10)
)
def forward(self, x):
x = self.model(x)
return x
3.加载数据集
train_data = torchvision.datasets.CIFAR10(root="CIFAR10", train=True, transform=torchvision.transforms.ToTensor(),download=True)
test_data = torchvision.datasets.CIFAR10(root="CIFAR10", train=False, transform=torchvision.transforms.ToTensor(),download=True)
4.设置模型和参数
# 创建网络模型
module = Module()
# 损失函数
loss_fn = nn.CrossEntropyLoss()
# 优化器
learning_rate = 1e-2
optimizer = torch.optim.SGD(module.parameters(), lr=learning_rate)
# 训练的轮数
epoch = 12
# 储存路径
work_dir = './LeNet'
# 添加tensorboard
writer = SummaryWriter("{}/logs".format(work_dir))
5.开始训练
for i in range(epoch):
print("-------epoch {} -------".format(i+1))
# 训练步骤
module.train()
for step, [imgs, targets] in enumerate(train_dataloader):
outputs = module(imgs)
loss = loss_fn(outputs, targets)
# 优化器
optimizer.zero_grad()
loss.backward()
optimizer.step()
train_step = len(train_dataloader)*i+step+1
if train_step % 100 == 0:
print("train time:{}, Loss: {}".format(train_step, loss.item()))
writer.add_scalar("train_loss", loss.item(), train_step)
# 测试步骤
module.eval()
total_test_loss = 0
total_accuracy = 0
with torch.no_grad():
for imgs, targets in test_dataloader:
outputs = module(imgs)
loss = loss_fn(outputs, targets)
total_test_loss = total_test_loss + loss.item()
accuracy = (outputs.argmax(1) == targets).sum()
total_accuracy = total_accuracy + accuracy
print("test set Loss: {}".format(total_test_loss))
print("test set accuracy: {}".format(total_accuracy/len(test_data)))
writer.add_scalar("test_loss", total_test_loss, i)
writer.add_scalar("test_accuracy", total_accuracy/len(test_data), i)
torch.save(module, "{}/module_{}.pth".format(work_dir,i+1))
print("saved epoch {}".format(i+1))
writer.close()