首页 > 其他分享 >实验五:全连接神经网络手写数字识别实验

实验五:全连接神经网络手写数字识别实验

时间:2022-11-29 13:44:06浏览次数:44  
标签:nn torch running batch 神经网络 实验 test 手写 size


【实验目的】

理解神经网络原理,掌握神经网络前向推理和后向传播方法;

掌握使用pytorch框架训练和推理全连接神经网络模型的编程实现方法。

【实验内容】

1.使用pytorch框架,设计一个全连接神经网络,实现Mnist手写数字字符集的训练与识别。

 

【实验报告要求】

修改神经网络结构,改变层数观察层数对训练和检测时间,准确度等参数的影响;
修改神经网络的学习率,观察对训练和检测效果的影响;
修改神经网络结构,增强或减少神经元的数量,观察对训练的检测效果的影响。

import torch
import numpy as np
from matplotlib import pyplot as plt
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision import datasets
import torch.nn.functional as F

batch_size = 64
learning_rate = 0.01
momentum = 0.5
EPOCH = 10

transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
train_dataset = datasets.MNIST(root='./data/mnist', train=True, transform=transform) 
test_dataset = datasets.MNIST(root='./data/mnist', train=False, transform=transform) 

train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)

class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = torch.nn.Sequential(
            torch.nn.Conv2d(1, 10, kernel_size=5),
            torch.nn.ReLU(),
            torch.nn.MaxPool2d(kernel_size=2),
        )
        self.conv2 = torch.nn.Sequential(
            torch.nn.Conv2d(10, 20, kernel_size=5),
            torch.nn.ReLU(),
            torch.nn.MaxPool2d(kernel_size=2),
        )
        self.fc = torch.nn.Sequential(
            torch.nn.Linear(320, 50),
            torch.nn.Linear(50, 10),
        )

    def forward(self, x):
        batch_size = x.size(0)
        x = self.conv1(x)  
        x = self.conv2(x)  
        x = x.view(batch_size, -1)  
        x = self.fc(x)
        return x 

model = Net()

criterion = torch.nn.CrossEntropyLoss()  
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate, momentum=momentum)  

def train(epoch):
    running_loss = 0.0  
    running_total = 0
    running_correct = 0
    for batch_idx, data in enumerate(train_loader, 0):
        inputs, target = data
        optimizer.zero_grad()
       
        outputs = model(inputs)
        loss = criterion(outputs, target)
        loss.backward()
        optimizer.step()
      
        running_loss += loss.item()
       
        _, predicted = torch.max(outputs.data, dim=1)
        running_total += inputs.shape[0]
        running_correct += (predicted == target).sum().item()
        if batch_idx % 300 == 299: 
            print('[%d, %5d]: loss: %.3f , acc: %.2f %%'
                  % (epoch + 1, batch_idx + 1, running_loss / 300, 100 * running_correct / running_total))
            running_loss = 0.0  
            running_total = 0
            running_correct = 0 
def test():
    correct = 0
    total = 0
    with torch.no_grad():  
        for data in test_loader:
            images, labels = data
            outputs = model(images)
            _, predicted = torch.max(outputs.data, dim=1) 
            total += labels.size(0)  
            correct += (predicted == labels).sum().item()
    acc = correct / total
    print('[%d / %d]: Accuracy on test set: %.1f %% ' % (epoch+1, EPOCH, 100 * acc))  
    return acc

if __name__ == '__main__':
    acc_list_test = []
    for epoch in range(EPOCH):
        train(epoch)
        acc_test = test()
        acc_list_test.append(acc_test)

 

 

 

 

 

 

y_test=acc_list_test
plt.plot(y_test)
plt.xlabel("Epoch")
plt.ylabel("Accuracy On TestSet")
plt.show()

 

 

标签:nn,torch,running,batch,神经网络,实验,test,手写,size
From: https://www.cnblogs.com/macheng1234/p/16935185.html

相关文章

  • STM32f103Zet6 跑马灯实验
    一、硬件  LED0(DS0)和LED1(DS1)分别接在PB5和PE5上,低电平LED亮。 在CubeMX中,将PB5,PE5设为GPIO_Output. 二、软件HAL库:HAL_GPIO_WritePin(GPIOB,G......
  • AWS上DevOps实验(二)--- 使用Terraform创建VPC网络
    从本文档起,作者计划在AWS上做一系列DevOps/IaC相关实验,本文是第二篇,使用Terraform创建VPC网络。本次实验架构图Terraform代码执行主文件main.tf#terraformcodetod......
  • 实验5 继承和多态
    实验任务四:pets.hpp:#pragmaonce#include<iostream>#include<string>std::string;usingnamespacestd;classMachinePets{public:MachinePets(constst......
  • 实验五 继承和多态
    task4//pets.hpp#include<iostream>usingnamespacestd;classMachinePets{private:stringnickname;public:MachinePets(conststrings):n......
  • 实验五:全连接神经网络手写数字识别实验
    实验五:全连接神经网络手写数字识别实验【实验目的】理解神经网络原理,掌握神经网络前向推理和后向传播方法;掌握使用pytorch框架训练和推理全连接神经网络模型的编程......
  • 实验五
    pets.hpp:#include<iostream>#include<string>usingnamespacestd;classMachinePets{private:stringnickname;public:MachinePets(){}Machine......
  • 实验置信区间
    转载:https://www.4vv4.com/article/197.html如何计算置信区间?要计算置信区间,请先计算样本的均值和标准误。请记住,您必须使用z得分针对所选的置信度水平来计算置信区间的......
  • 实验五
    task4.cpp:#pragmaonce#include<iostream>#include<string>usingnamespacestd;classMachinePets{public: MachinePets(conststrings):nickname{s}{} v......
  • 实验五
    #include<iostream>#include"pets.hpp"voidplay(MachinePets&obj){std::cout<<obj.get_nickname()<<"says"<<obj.talk()<<std::endl;}voidtest......
  • matlab使用长短期记忆(LSTM)神经网络对序列数据进行分类|附代码数据
    全文下载链接:http://tecdat.cn/?p=19751本示例说明如何使用长短期记忆(LSTM)网络对序列数据进行分类。最近我们被客户要求撰写关于LSTM的研究报告,包括一些图形和统计输出......