摘要
1 文献阅读 2 深度学习实践:实践手写数字识别的代码 3 任务项目:将虚拟机文件与虚拟机配置文件打包好,上传至云盘,只需最后下载。 4 带毕设:沟通进度情况
深度学习实践
手写数字识别代码: 一、搭建模型Model.py,构造一个CNN模型
import torch
from torch import nn
from torch.utils.tensorboard import SummaryWriter
class CnnModel(nn.Module):
def __init__(self):
super(CnnModel, self).__init__()
self.x1 = torch.ones(1, 3, 5, 5)
self.model1 = nn.Sequential(
nn.Conv2d(in_channels=1, out_channels=3, kernel_size=3, stride=1, padding=0),
nn.MaxPool2d(2),
nn.Conv2d(3, 3, 3, 1, 0),
nn.MaxPool2d(2)
)
self.model2 = nn.Sequential(
nn.Flatten(),
nn.Linear(75, 10),
nn.Softmax(1)
)
def forward(self, x):
self.x1 = self.model1(x)
x = self.model2(self.x1)
return x
if __name__ == '__main__':
x = torch.ones(1, 1, 28, 28)
model = CnnModel()
output = model.forward(x)
writer = SummaryWriter("./logs_model")
writer.add_graph(model, x)
writer.close()
二、导入训练集,导入模型进行训练的Minist_model.py
import torch
import torchvision
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from Model import *
trans_tensor = torchvision.transforms.ToTensor()
train_data = torchvision.datasets.MNIST("./data_minst", train=True, transform=trans_tensor, download=True)
test_data = torchvision.datasets.MNIST("./data_minst", train=False, transform=trans_tensor, download=True)
print(train_data)
writer =SummaryWriter("./logs")
batch = 50
train_data_batch = DataLoader(train_data, batch_size=batch)
test_data_batch = DataLoader(test_data, batch_size=batch)
MinModel = CnnModel()
learingrate = 1e-2
optimizer = torch.optim.SGD(MinModel.parameters(), lr=learingrate)
loss_f = nn.CrossEntropyLoss()
epoach = 12
train_size = 1
for i in range(epoach):
total_loss = 0
print("——————————第{}轮训练开始——————————————".format(i+1))
for data in train_data_batch:
img, label = data
y = MinModel(img)
loss = loss_f(y, label)
writer.add_scalar("Loss值随训练次数的变化", loss, train_size)
total_loss += loss
optimizer.zero_grad()
loss.backward()
optimizer.step()
acc_train = ((y.argmax(1)==label).sum())/batch
writer.add_scalar("准确率随训练次数的变化", acc_train, train_size)
if(train_size%100==0):
print("第{}次训练的loss值为{}".format(train_size, loss))
train_size += 1
print("********第{}轮训练全部的loss值是:{}***********".format(i+1, total_loss))
torch.save(MinModel, "./Model_save/model.pth")
writer.close()
Minist_model.py将CNN模型导入,以train=true从数据集中导入训练数据、以train=false从数据集中导入测试数据,读取训练图片并转换成tensor型数据,将训练结果输出到logs文件中,将训练好的模型保存到model.pth文件中。
三、Minist_test.py测试模型准确率
import torch
import torchvision.transforms
from Model import *
trans_tensor = torchvision.transforms.ToTensor()
test_dataset = torchvision.datasets.MNIST("./data_minst", train=False, transform=trans_tensor, download=True)
Model_test = torch.load("Model_save/model.pth")
writer = SummaryWriter("./test_logs", )
img, label = test_dataset[0]
img = torch.reshape(img, (1, 1, 28, 28))
test_output = Model_test(img)
writer.add_images("输出图片", Model_test.x1)
print(test_output)
print(label)
取测试数据,调用训练好的模型,输出test_logs文件。 训练过程如下图所示。
在终端输入命令
tensorboard --logdir="logs"
得到可视化结果,如下图所示。
|