class Dataset(object):
"""An abstract class representing a Dataset.
All other datasets should subclass it. All subclasses should override
``__len__``, that provides the size of the dataset, and ``__getitem__``,
supporting integer indexing in range from 0 to len(self) exclusive.
"""
def __getitem__(self, index):
raise NotImplementedError
def __len__(self):
raise NotImplementedError
def __add__(self, other):
return ConcatDataset([self, other])
import torch
from torch import nn
from torch.nn import Sequential,Conv2d,MaxPool2d,Flatten
from torch.nn import Linear
from torch.utils.tensorboard import SummaryWriter
import torchvision
import torchvision.transforms
from torch.utils.data import DataLoader
dataset = torchvision.datasets.CIFAR10("./dataset",train=False,transform=torchvision.transforms.ToTensor(),
download=True)
dataloader = DataLoader(dataset, batch_size=64)
class MY_Dodule(nn.Module):
def __init__(self):
super(MY_Dodule,self).__init__()
self.model = Sequential(
Conv2d(3, 32, kernel_size=5, padding=2),
MaxPool2d(2),
Conv2d(32, 32, kernel_size=5, padding=2),
MaxPool2d(2),
Conv2d(32, 64, kernel_size=5, padding=2),
MaxPool2d(2),
Flatten(),
Linear(1024,64),
Linear(64,10)
)
def forward(self,input):
output = self.model(input)
return output
my_module = MY_Dodule()
loss = nn.CrossEntropyLoss()
optim = torch.optim.SGD(my_module.parameters(),lr=0.1)
for epoch in range(20):
running_loss = 0.0
for data in dataloader:
images,targets = data
input = images
output = my_module(input) # 前向转播
result_loss = loss(output,targets) # 计算损失
optim.zero_grad() # 清除之前的梯度
result_loss.backward() # 反向转播
optim.step() #梯度更新
running_loss += result_loss
pass
print(running_loss)
pass
torchvision.models.vgg16(pretrained,progress):PyTorch 中的一个类,是用来加载预训练的 VGG-16 模型的函数。
在 VGG-16 模型中添加层:model是torchvision.models.vgg16()示例化对象,model.classifier.add_module(str,nn.Module)这个函数接受两个参数。
在 VGG-16 模型中修改层:model是torchvision.models.vgg16()示例化对象,model.classifier[n] = nn.Module
import torchvision
# 准备训练集
train_data = torchvision.datasets.CIFAR10("dataset",train=True,transform=torchvision.transforms.ToTensor(),
download=True)
# 准备测试集
test_data = torchvision.datasets.CIFAR10("dataset",train=False,transform=torchvision.transforms.ToTensor(),
download=True)
# 计算数据集长度
train_data_size = len(train_data)
test_data_size = len(test_data)
print("训练数据集的长度:{}".format(train_data_size))
print("测试数据集的长度:{}".format(test_data_size))
# dataloader()加载数据集
train_dataloader = DataLoader(train_data, batch_size=64)
test_dataloader = DataLoader(test_data, batch_size=64)
import torch
from torch import nn
class My_Module(nn.Module):
def __init__(self):
super(My_Module,self).__init__()
self.model = nn.Sequential(
nn.Conv2d(3, 32, kernel_size=5, stride=1, padding=2),
nn.MaxPool2d(2),
nn.Conv2d(32 ,32, kernel_size=5, stride=1, padding=2),
nn.MaxPool2d(2),
nn.Conv2d(32,64,5,1,2),
nn.MaxPool2d(2),
nn.Flatten(),
nn.Linear(64*4*4,64),
nn.Linear(64,10),
)
def forward(self,input):
output = self.model(input)
return output
if __name__ == '__main__':
my_module = My_Module()
input = torch.ones((64, 3, 32, 32))
output = my_module(input)
print(output.shape)
# 创建网络模型
my_module = My_Module()
loss_f = nn.CrossEntropyLoss()
# 定义优化器,进行梯度下降
learning_rate = 0.01 # 学习效率
optimizer = torch.optim.SGD(my_module, lr=learning_rate)
# 设置训练网络模型的一些参数
total_train_step = 0 # 记录训练次数
total_test_step = 0 # 记录测试次数
epoch = 10 # 训练的轮次
writer = SummaryWriter("P27") # 添加tensorboard
# 训练网络模型
for i in range(epoch):
print("------第{}轮训练开始------".format(i + 1))
# 训练步骤开始
for data in train_dataloader:
images ,targets = data
input = images
output = my_module(input) # 前向传播
loss = loss_f(output, targets) # 计算损失
loss.backward() # 反向转播
optimizer.zero_grad() #
optimizer.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)
# 测试步骤开始
total_test_loss = 0
total_accuracy = 0
with torch.no_grad():
for data in test_data:
images, targets = data
inputs = images
outputs = my_module(inputs)
loss = loss_f(outputs,targets)
total_test_loss = total_test_loss + loss.item()
accuracy = (outputs.argmax(1) == targets).sum()
total_accuracy = total_accuracy + accuracy
print("整体测试集上的loss:{}".format(total_test_loss))
print("整体测试集上的正确率:{}".format(total_accuracy / test_data_size))
writer.add_scalar("test_loss",total_test_loss,total_test_step)
writer.add_scalar("test_accuracy",total_accuracy / test_data_size,total_test_step)
total_test_step = total_test_step + 1
torch.save(my_module,"my_mudule_{}.pth".format(i))
writer.close()