pytorch前馈神经网络--手写数字识别

news2024/9/28 18:37:30

前言

具体内容就是:

输入一个图像,经过神经网络后,识别为一个数字。从而实现图像的分类。

资源:

https://download.csdn.net/download/fengzhongye51460/89578965

思路:

确定输入的图像:会单通道灰度的28*28的图像,

把图像平铺后,输送到784个神经元的输入层

输入层输送到隐藏层,提取特征

隐藏层输送到输出层,显示概率

初始化模型

import torch  # Import PyTorch
from torch import nn  # Import the neural network module from PyTorch

# Define the neural network class, inheriting from nn.Module
class Network(nn.Module):
    def __init__(self):
        super().__init__()  # Call the initializer of the parent class nn.Module
        self.layer1 = nn.Linear(784, 256)  # Define the first linear layer (input size 784, output size 256)
        self.layer2 = nn.Linear(256, 10)  # Define the second linear layer (input size 256, output size 10)

    def forward(self, x):
        x = x.view(-1, 28*28)  # Flatten the input tensor to a 1D tensor of size 28*28
        x = self.layer1(x)  # Pass the input through the first linear layer
        x = torch.relu(x)  # Apply the ReLU activation function
        return self.layer2(x)  # Pass the result through the second linear layer and return it

__init__中

在输入层和隐藏层之间,创建一个线性层1 ,784个神经元转为256个

在隐藏层和输出层之间,创建一个线性层2,把256个神经元转为10个

forward中

先把输入图像x展平,然后输送到layer1中,用relu激活,再输送至layer2

训练模型

import torch
from torch import nn
from torch import optim
from model import Network
from torchvision import transforms
from torchvision import datasets
from torch.utils.data import DataLoader

if __name__ == '__main__':
    # Define the image transformations: convert to grayscale and then to tensor
    transform = transforms.Compose([
        transforms.Grayscale(num_output_channels=1),
        transforms.ToTensor()
    ])

    # Load the training dataset from the specified directory and apply transformations
    train_dataset = datasets.ImageFolder(root='./mnist_train', transform=transform)
    # Load the test dataset from the specified directory and apply transformations
    test_dataset = datasets.ImageFolder(root='./mnist_test', transform=transform)
    # Print the length of the training dataset
    print("train_dataset length: ", len(train_dataset))
    # Print the length of the test dataset
    print("test_dataset length: ", len(test_dataset))

    # Create a DataLoader for the training dataset with batch size of 64 and shuffling enabled
    train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
    # Print the number of batches in the training DataLoader
    print("train_loader length: ", len(train_loader))

    # Iterate over the first few batches of the training DataLoader
    for batch_idx, (data, label) in enumerate(train_loader):
        # Uncomment the following lines to break after 3 batches
        # if batch_idx == 3:
        #     break
        # Print the batch index
        print("batch_idx: ", batch_idx)
        # Print the shape of the data tensor
        print("data.shape: ", data.shape)
        # Print the shape of the label tensor
        print("label.shape: ", label.shape)
        # Print the labels
        print(label)

    # Initialize the neural network model
    model = Network()
    # Initialize the Adam optimizer with the model's parameters
    optimizer = optim.Adam(model.parameters())
    # Define the loss function as cross-entropy loss
    criterion = nn.CrossEntropyLoss()

    # Train the model for 10 epochs
    for epoch in range(10):
        # Iterate over the batches in the training DataLoader
        for batch_idx, (data, label) in enumerate(train_loader):
            # Forward pass: compute the model output
            output = model(data)
            # Compute the loss
            loss = criterion(output, label)
            # Backward pass: compute the gradients
            loss.backward()
            # Update the model parameters
            optimizer.step()
            # Zero the gradients for the next iteration
            optimizer.zero_grad()
            # Print the loss every 100 batches
            if batch_idx % 100 == 0:
                print(f"Epoch {epoch + 1}/10 "
                      f"| Batch {batch_idx}/{len(train_loader)} "
                      f"| Loss: {loss.item():.4f}")

    # Save the trained model's state dictionary to a file
    torch.save(model.state_dict(), 'mnist.pth')

1.数据的读取

        先把图像灰度化,然后转换为张量

    transform = transforms.Compose([
        transforms.Grayscale(num_output_channels=1),
        transforms.ToTensor()
    ])

导入训练数据和测试数据,

    # Load the training dataset from the specified directory and apply transformations
    train_dataset = datasets.ImageFolder(root='./mnist_train', transform=transform)
    # Load the test dataset from the specified directory and apply transformations
    test_dataset = datasets.ImageFolder(root='./mnist_test', transform=transform)
    # Print the length of the training dataset
    print("train_dataset length: ", len(train_dataset))
    # Print the length of the test dataset
    print("test_dataset length: ", len(test_dataset))
    # Create a DataLoader for the training dataset with batch size of 64 and shuffling enabled
    train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
    # Print the number of batches in the training DataLoader
    print("train_loader length: ", len(train_loader))

会把文件夹名称作为数据的标签

,例如 名称为0的文件夹,下面所有的文件都是数字0的图片

打印信息

可以看到导入了6w张训练图片,1w张测试图片,和60000/64=938 组数据

2.数据的训练

创建模型,设置优化器和损失函数

    # Initialize the neural network model
    model = Network()
    # Initialize the Adam optimizer with the model's parameters
    optimizer = optim.Adam(model.parameters())
    # Define the loss function as cross-entropy loss
    criterion = nn.CrossEntropyLoss()

训练数据

训练10轮 ,

每次的步骤

1.计算神经网络的前向传播结果

2.计算output和标签label之间的损失loss

3.使用backward计算梯度

4.使用optimizer更新参数

5.将梯度清零

    # Train the model for 10 epochs
    for epoch in range(10):
        # Iterate over the batches in the training DataLoader
        for batch_idx, (data, label) in enumerate(train_loader):
            # Forward pass: compute the model output
            output = model(data)
            # Compute the loss
            loss = criterion(output, label)
            # Backward pass: compute the gradients
            loss.backward()
            # Update the model parameters
            optimizer.step()
            # Zero the gradients for the next iteration
            optimizer.zero_grad()
            # Print the loss every 100 batches
            if batch_idx % 100 == 0:
                print(f"Epoch {epoch + 1}/10 "
                      f"| Batch {batch_idx}/{len(train_loader)} "
                      f"| Loss: {loss.item():.4f}")

3.保存模型

    # Save the trained model's state dictionary to a file
    torch.save(model.state_dict(), 'mnist.pth')

测试模型

代码

from model import Network  # Import the custom neural network model class
from torchvision import transforms  # Import torchvision transformations
from torchvision import datasets  # Import torchvision datasets
import torch  # Import PyTorch

if __name__ == '__main__':
    # Define the image transformations: convert to grayscale and then to tensor
    transform = transforms.Compose([
        transforms.Grayscale(num_output_channels=1),
        transforms.ToTensor()
    ])

    # Load the test dataset from the specified directory and apply transformations
    test_dataset = datasets.ImageFolder(root='./mnist_test', transform=transform)
    # Print the length of the test dataset
    print("test_dataset length: ", len(test_dataset))

    # Initialize the neural network model
    model = Network()
    # Load the model's state dictionary from the saved file
    model.load_state_dict(torch.load('mnist.pth'))

    right = 0  # Initialize a counter for correctly classified images

    # Iterate over the test dataset
    for i, (x, y) in enumerate(test_dataset):
        output = model(x.unsqueeze(0))  # Forward pass: add batch dimension and compute the model output
        predict = output.argmax(1).item()  # Get the index of the highest score as the predicted label
        if predict == y:
            right += 1  # Increment the counter if the prediction is correct
        else:
            img_path = test_dataset.samples[i][0]  # Get the path of the misclassified image
            # Print details of the misclassified case
            print(f"wrong case: predict = {predict} actual = {y} img_path = {img_path}")

    sample_num = len(test_dataset)  # Get the total number of samples in the test dataset
    acc = right * 1.0 / sample_num  # Calculate the accuracy as the ratio of correct predictions
    # Print the test accuracy
    print("test accuracy = %d / %d = %.31f" % (right, sample_num, acc))

1.读取测试数据集

    # Define the image transformations: convert to grayscale and then to tensor
    transform = transforms.Compose([
        transforms.Grayscale(num_output_channels=1),
        transforms.ToTensor()
    ])

    # Load the test dataset from the specified directory and apply transformations
    test_dataset = datasets.ImageFolder(root='./mnist_test', transform=transform)
    # Print the length of the test dataset
    print("test_dataset length: ", len(test_dataset))

查看打印信息,导入了1w张测试图片

2.导入模型

    # Initialize the neural network model
    model = Network()
    # Load the model's state dictionary from the saved file
    model.load_state_dict(torch.load('mnist.pth'))

3.测试

将测试图片导入模型

output = model(x.unsqueeze(0))  # Forward pass: add batch dimension and compute the model output

选择概率最大的测试标签

predict = output.argmax(1).item()  # Get the index of the highest score as the predicted label

查看结果

可以看到,1w图片中9807张图片识别正确。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1948896.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

即时战略游戏:帝国时代2 for Mac 3.3.1769 中文移植版

帝国时代II蛮王崛起是一款非常经典的即时战略游戏,新的地图,四个新战役,新的AI进行整合。帝国时代2玩家将要探索来自“国王时代”和“征服者”扩张的所有原始单人游戏,选择跨越一千年历史的18个文明,并在线上挑战其他玩…

17 敏捷开发—Scrum(2)

从上一篇 「16 敏捷开发实践(1)」中了解了Scrum是一个用于开发和维护复杂产品的框架,是一个增量的、迭代的开发过程。一般由多个Sprint(迭代冲刺)组成,每个Sprint长度一般为2-4周。下面全面介绍Scrumde 角色…

2024第29届郑州全国商品交易会

第29届郑州全国商品交易会 2024第四届餐饮与供应链专题展 邀 请 函郑州全国商品交易会(简称郑交会)是全国大型性经贸活动,一直秉承“政府指导,市场化运作”的模式,自1995年以来已成功举办了二十八届,是国内…

k8s多集群管理工具kubecm

文章目录 一、概述二、安装1、官网链接2、各平台安装2.1、MacOS2.2、Linux2.3、Windows 三、实例1、验证2、配置kubecm自动补全(选做)2.1、Bash2.2、Zsh2.3、fish2.4、PowerShell 3、创建存放kubeconfig文件的目录4、添加到 $HOME/.kube/config4.1、kube…

Pytorch笔记1

建议点赞收藏关注!持续更新至pytorch大部分内容更完。 整体框架如下 目录 gpu加速数据数据结构张量TensorVariable 预处理数据增强 模型构建模块组织复杂网络初始化网络参数定义网络层 损失函数创建损失函数设置损失函数超参数选择损失函数 优化器管理模型参数管理…

JavaWeb学习——请求响应、分层解耦

目录 一、请求响应学习 1、请求 简单参数 实体参数 数组集合参数 日期参数 Json参数 路径参数 总结 2、响应 ResponseBody&统一响应结果 二、分层解耦 1、三层架构 三层架构含义 架构划分 2、分层解耦 引入概念 容器认识 3、IOC&DI入门 4、IOC详解 …

SSM学习9:SpringBoot简介、创建项目、配置文件、多环节配置

简介 SpringBoot式用来简化Spring应用的初始搭建以及开发过程的一个框架 项目搭建 File -> New -> Project 选中pom.xml文件,设置为maven项目 项目启动成功 可以访问BasicController中的路径 配置文件 在resources目录下 application.properties 默…

【初阶数据结构】8.二叉树(3)

文章目录 4.实现链式结构二叉树4.1 前中后序遍历4.1.1 遍历规则4.1.2 代码实现 4.2 结点个数以及高度等4.3 层序遍历4.4 判断是否为完全二叉树4.5层序遍历和判断是否为完全二叉树完整代码 4.实现链式结构二叉树 用链表来表示一棵二叉树,即用链来指示元素的逻辑关系…

巴斯勒相机(Basler) ACE2 dart 系列说明和软件

巴斯勒相机(Basler) ACE2 dart 系列说明和软件

NeuralGCM:革新气候预测的机器学习新纪元

在地球变暖成为全球关注焦点的今天,精确预测气候变化及其影响成为了科学界亟待解决的重大课题。传统基于物理的气候模型(GCM,全球气候模型)在预测大气、海洋、冰层等复杂系统时虽已取得显著进展,但计算成本高、耗时长且…

系统模块时序图的重要性:解锁系统模块交互的全景视图

在复杂的系统开发中,理解和管理不同模块之间的交互是成功的关键。时序图是一种有效的工具,可以帮助我们清晰地展示这些交互,提升设计和开发的效率。本文将深入探讨系统模块之间的时序图,并通过实例展示其实际应用。 1. 什么是系统模块之间的时序图? 系统模块之间的时序图…

Eclipse 生成 jar 包

打开 Jar 文件向导 Jar 文件向导可用于将项目导出为可运行的 jar 包。 打开向导的步骤为: 在 Package Explorer 中选择你要导出的项目内容。如果你要导出项目中所有的类和资源,只需选择整个项目即可。点击 File 菜单并选择 Export。在输入框中输入"JAR"…

Robot Operating System——Parameter设置的预处理、校验和成功回调

大纲 预处理校验成功回调完整代码测试总结 在《Robot Operating System——对Parameter设置进行校验》一文中,我们通过Node的add_on_set_parameters_callback方法,设置了一个回调函数,用于校验传递过来的Parameter参数。但是这个方法并不能对…

【UbuntuDebian安装Nginx】在线安装Nginx

云计算:腾讯云轻量服务器 操作系统:Ubuntu-v22 1.更新系统软件包列表 打开终端并运行以下命令来确保你的系统软件包列表是最新的: sudo apt update2.安装 Nginx 使用以下命令安装 Nginx: sudo apt install nginx3.启动 Nginx…

基于python的BP神经网络回归模型

1 导入必要的库 import pandas as pd from sklearn.model_selection import train_test_split, cross_val_score, KFold import xgboost as xgb from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error, r2_score …

电脑如何进行录屏?电脑录屏无压力!

在数字时代,屏幕录制已成为我们日常生活和工作中不可或缺的一部分。无论你是想要制作教程、记录游戏过程,还是捕捉在线会议的精彩瞬间,掌握屏幕录制的方法都显得尤为重要。本文将为你详细介绍电脑如何进行录屏,帮助你轻松捕捉屏幕…

音视频入门基础:H.264专题(17)——FFmpeg源码获取H.264裸流文件信息(视频压缩编码格式、色彩格式、视频分辨率、帧率)的总流程

音视频入门基础:H.264专题系列文章: 音视频入门基础:H.264专题(1)——H.264官方文档下载 音视频入门基础:H.264专题(2)——使用FFmpeg命令生成H.264裸流文件 音视频入门基础&…

科技核心 电力方向

【电力投资】电力体制改革***电量投资风险控制研究 【配电网管理】基于***配电网线损数据精细化管理研究 【电价优化】基于***能源系统电价优化模型研究 【电力营销】基于***电力营销业务数据***

用python程序发送文件(python实例二十六)

目录 1.认识Python 2.环境与工具 2.1 python环境 2.2 Visual Studio Code编译 3.文件上传 3.1 代码构思 3.2 服务端代码 3.3 客户端代码 3.4 运行结果 4.总结 1.认识Python Python 是一个高层次的结合了解释性、编译性、互动性和面向对象的脚本语言。 Python 的设计具…

SqlSugar删除没有定义主键的实体类对应的数据库表数据

一般而言,使用SqlSugar的DbFirst功能创建数据库表实体类时,如果数据库表有主键,生成的实体类对应属性也会标识为主键,如下图所示。   但有时候生成的实体类没有自动配置主键,这时可以通过以下方式进行删除操作&…