(联邦学习笔记,资料来源于b站小土堆)
1、准备数据集
2、获取数据集长度,可以用来辅助计算精确度
3、加载数据集(DataLoader)
4、搭建网络模型(一般单独一个python文件)
5、创建网络模型(实例化)
6、定义损失函数、优化器
7、设置训练网络的一些参数(如训练次数、轮数等等)
8、模型训练
具体代码实现如下(简单示例):
1、准备数据集
train_data = torchvision.datasets.CIFAR10("../data",train=True,transform=torchvision.transforms.ToTensor(),download=True)
test_data = torchvision.datasets.CIFAR10("../data",train=False,transform=torchvision.transforms.ToTensor(),download=True)
2、获取数据集长度
#获取数据集长度,可以判断整体的测试精度
train_data_len = len(train_data)
test_data_len = len(test_data)
print("训练数据集长度:{}".format(test_data_len))
print("测试数据集长度:{}".format(train_data_len))
3、加载数据集(DataLoader)
#加载数据集
train_dataloader = DataLoader(train_data,batch_size=64)
test_dataloader = DataLoader(test_data,batch_size=64)
4、搭建网络模型(一般单独一个python文件)
import torch
from torch import nn
from torch.nn import Conv2d, MaxPool2d, Flatten, Linear
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = Conv2d(3,32,5,1,2)
self.maxpool1 = MaxPool2d(2)
self.conv2 = Conv2d(32,32,5,1,2)
self.maxpool2 = MaxPool2d(2)
self.conv3 = Conv2d(32,64,5,1,2)
self.maxpool3 = MaxPool2d(2)
self.flatten = Flatten()
self.linear1 = Linear(1024,64)
self.linear2 = Linear(64,10)
def forward(self,x):
x = self.conv1(x)
x = self.maxpool1(x)
x = self.conv2(x)
x = self.maxpool2(x)
x = self.conv3(x)
x = self.maxpool3(x)
x = self.flatten(x)
x = self.linear1(x)
x = self.linear2(x)
return x
5、创建网络模型(实例化)
#创建模型
model = MyModel()
6、定义损失函数、优化器
#定义损失函数
loss_fn = nn.CrossEntropyLoss()
#定义优化器
#reaning_rate = 0.01
#1e-2 = 1 x (10)^(-2) = 1/100 = 0.01
reaning_rate = 1e-2
optimer = torch.optim.SGD(model.parameters(),lr=reaning_rate)
7、设置训练网络的一些参数(如训练次数、轮数等等)
#设置训练网络模型的一些参数
#记录训练的次数
total_train_step = 0
#记录测试的次数
total_test_step = 0
#训练的轮数
epoch = 10
#添加tensorboard来绘图
writer = SummaryWriter("../logs_train")
8、模型训练
#训练模型
for i in range(epoch):
print("-------------第 {} 轮训练开始--------------".format(i+1))
#训练开始
for data in train_dataloader:
imgs,targets = data
outputs = model(imgs)
loss = loss_fn(outputs,targets)
#优化器优化模型
#清空梯度
optimer.zero_grad()
#反向传播
loss.backward()
#更新梯度
optimer.step()
total_train_step = total_train_step + 1
if total_train_step % 100 == 0:
print("训练次数:{},Loss:{}".format(total_train_step,loss.item()))
writer.add_scalar("train_loss",loss.item(),total_train_step)
#测试步骤开始
#在with里的代码没有梯度,不记梯度
total_test_loss = 0
#记录正确率
total_accuracy = 0
with torch.no_grad():
for data in test_dataloader:
imgs,targets =data
outputs = model(imgs)
loss = loss_fn(outputs,targets)
total_test_loss = total_test_loss + loss
#outputs.argmax()可以判断输出和目标是否一致,sum()求和,可以知道总共正确的个数
accuracy = (outputs.argmax(1) == targets).sum()
total_accuracy = total_accuracy + accuracy
print("整体测试集上的Loss:{}".format(total_test_loss))
print("整体测试集上的正确率:{}".format(total_accuracy/test_data_len))
writer.add_scalar("test_loss",total_test_loss.item(),total_test_step)
writer.add_scalar("test_acc",total_accuracy/test_data_len,total_test_step)
total_test_step = total_test_step + 1
#保存模型
#torch.save(model.state_dict(),"model_{}.pth".format(i))
torch.save(model,"model_{}.pth".format(i))
print("第 {} 轮模型已保存!".format(i+1))
writer.close()
完整代码:
模型单独一个py文件
import torch
from torch import nn
from torch.nn import Conv2d, MaxPool2d, Flatten, Linear
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = Conv2d(3,32,5,1,2)
self.maxpool1 = MaxPool2d(2)
self.conv2 = Conv2d(32,32,5,1,2)
self.maxpool2 = MaxPool2d(2)
self.conv3 = Conv2d(32,64,5,1,2)
self.maxpool3 = MaxPool2d(2)
self.flatten = Flatten()
self.linear1 = Linear(1024,64)
self.linear2 = Linear(64,10)
def forward(self,x):
x = self.conv1(x)
x = self.maxpool1(x)
x = self.conv2(x)
x = self.maxpool2(x)
x = self.conv3(x)
x = self.maxpool3(x)
x = self.flatten(x)
x = self.linear1(x)
x = self.linear2(x)
return x
#测试模型
if __name__=='__main__':
mymodel = MyModel()
#数据是64张图片,3通道,大小32x32
inputs = torch.ones((64,3,32,32))
outputs = mymodel(inputs)
#outputs.shape=torch.Size([64,10]),返回的是64行数据,每行有10个数据,每个数据代表该图片属于该类(10个类别)的概率
print(outputs.shape)
模型训练单独一个py文件:
import torchvision
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from model import *
from torch import nn
#准备数据集
train_data = torchvision.datasets.CIFAR10("../data",train=True,transform=torchvision.transforms.ToTensor(),download=True)
test_data = torchvision.datasets.CIFAR10("../data",train=False,transform=torchvision.transforms.ToTensor(),download=True)
#获取数据集长度,可以判断整体的测试精度
train_data_len = len(train_data)
test_data_len = len(test_data)
print("训练数据集长度:{}".format(test_data_len))
print("测试数据集长度:{}".format(train_data_len))
#加载数据集
train_dataloader = DataLoader(train_data,batch_size=64)
test_dataloader = DataLoader(test_data,batch_size=64)
#创建模型
model = MyModel()
#定义损失函数
loss_fn = nn.CrossEntropyLoss()
#定义优化器
#reaning_rate = 0.01
#1e-2 = 1 x (10)^(-2) = 1/100 = 0.01
reaning_rate = 1e-2
optimer = torch.optim.SGD(model.parameters(),lr=reaning_rate)
#设置训练网络模型的一些参数
#记录训练的次数
total_train_step = 0
#记录测试的次数
total_test_step = 0
#训练的轮数
epoch = 10
#添加tensorboard来绘图
writer = SummaryWriter("../logs_train")
#训练模型
for i in range(epoch):
print("-------------第 {} 轮训练开始--------------".format(i+1))
#训练开始
for data in train_dataloader:
imgs,targets = data
outputs = model(imgs)
loss = loss_fn(outputs,targets)
#优化器优化模型
#清空梯度
optimer.zero_grad()
#反向传播
loss.backward()
#更新梯度
optimer.step()
total_train_step = total_train_step + 1
if total_train_step % 100 == 0:
print("训练次数:{},Loss:{}".format(total_train_step,loss.item()))
writer.add_scalar("train_loss",loss.item(),total_train_step)
#测试步骤开始
#在with里的代码没有梯度,不记梯度
total_test_loss = 0
#记录正确率
total_accuracy = 0
with torch.no_grad():
for data in test_dataloader:
imgs,targets =data
outputs = model(imgs)
loss = loss_fn(outputs,targets)
total_test_loss = total_test_loss + loss
#outputs.argmax()可以判断输出和目标是否一致,sum()求和,可以知道总共正确的个数
accuracy = (outputs.argmax(1) == targets).sum()
total_accuracy = total_accuracy + accuracy
print("整体测试集上的Loss:{}".format(total_test_loss))
print("整体测试集上的正确率:{}".format(total_accuracy/test_data_len))
writer.add_scalar("test_loss",total_test_loss.item(),total_test_step)
writer.add_scalar("test_acc",total_accuracy/test_data_len,total_test_step)
total_test_step = total_test_step + 1
#保存模型
#torch.save(model.state_dict(),"model_{}.pth".format(i))
torch.save(model,"model_{}.pth".format(i))
print("第 {} 轮模型已保存!".format(i+1))
writer.close()
(如有不同意见,欢迎留下评论,我见到了会第一时间回复)