Mnist手写数字

运行实现:

python 复制代码
import torch
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision.datasets import MNIST
import matplotlib.pyplot as plt


class Net(torch.nn.Module):#net类神经网络主体

    def __init__(self):#4个全链接层
        super().__init__()
        self.fc1 = torch.nn.Linear(28*28, 64)#输入为28*28尺寸图像
        self.fc2 = torch.nn.Linear(64, 64)#中间三层都是64个节点
        self.fc3 = torch.nn.Linear(64, 64)
        self.fc4 = torch.nn.Linear(64, 10)#输出为10个数字类别
    
    def forward(self, x):#前向传播
        x = torch.nn.functional.relu(self.fc1(x))#先全连接线性计算,再套上激活函数
        x = torch.nn.functional.relu(self.fc2(x))
        x = torch.nn.functional.relu(self.fc3(x))
        x = torch.nn.functional.log_softmax(self.fc4(x), dim=1)#输出层用softmax做归一化,log_softmax是为了提高计算稳定性,套上了一个对数函数
        return x


def get_data_loader(is_train):#导入数据
    to_tensor = transforms.Compose([transforms.ToTensor()])#导入张量
    data_set = MNIST("", is_train, transform=to_tensor, download=True)#下载文件,""里面对应的是下载目录,is_train指定导入训练集还是测试集
    return DataLoader(data_set, batch_size=15, shuffle=True)#一个批次15张图片,shuffle=true说明数据是随机打乱的,返回数据加载器


def evaluate(test_data, net):#评估正确率
    n_correct = 0
    n_total = 0
    with torch.no_grad():
        for (x, y) in test_data:#取出数据
            outputs = net.forward(x.view(-1, 28*28))#计算神经网络预测值
            for i, output in enumerate(outputs):#作比较
                if torch.argmax(output) == y[i]:#argmax取最大预测概率的序号
                    n_correct += 1#累加正确的
                n_total += 1
    return n_correct / n_total


def main():

    train_data = get_data_loader(is_train=True)#训练集
    test_data = get_data_loader(is_train=False)#测试集
    net = Net()
    
    print("initial accuracy:", evaluate(test_data, net))#打印初始网络的正确率,接近0.1
    optimizer = torch.optim.Adam(net.parameters(), lr=0.001)#以下为pytorch固定写法
    for epoch in range(3):#epoch是轮次
        for (x, y) in train_data:
            net.zero_grad()#初始化
            output = net.forward(x.view(-1, 28*28))#正向传播
            loss = torch.nn.functional.nll_loss(output, y)#计算差值,null_loss对数损失函数,为了匹配前面log_softmax的对数运算
            loss.backward()#反向误差传播
            optimizer.step()#优化网络参数
        print("epoch", epoch, "accuracy:", evaluate(test_data, net))

    for (n, (x, _)) in enumerate(test_data):#抽取4张图像,显示预测结果
        if n > 3:
            break
        predict = torch.argmax(net.forward(x[0].view(-1, 28*28)))
        plt.figure(n)
        plt.imshow(x[0].view(28, 28),cmap='gray')
        plt.title("prediction: " + str(int(predict)))
    plt.show()


if __name__ == "__main__":
    main()

中间可能会报错误:(libiomp5md.dll问题)

python 复制代码
OMP: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized.

这个处理就是在anaconda文件夹下面搜索libiomp5md.dll,那bin下面的 libiomp5md.dll文件全部修改命名,就像我这样,两个bin文件夹下面的都改了。

运行结果:

两轮精确度如下:

4个数字预测图片如下:

相关推荐
饼干哥哥4 天前
开源Skills|搭建亚马逊动态关键词库系统,每天抓SSS级机会词
人工智能·深度学习·数据分析
武子康6 天前
调查研究-191 SenseVoice 不只是 ASR:把语音从“转文字“升级成“理解状态“
人工智能·深度学习·openai
武子康7 天前
调查研究-189 Kronos 调研:金融 K 线基础模型,是真突破,还是量化圈的新玩具?
人工智能·深度学习·openai
xiao5kou4chang6kai413 天前
MATLAB机器学习、深度学习--从数据预处理到模型训练
深度学习·机器学习·matlab·数据预处理
renhongxia113 天前
世界模型作为AGI落地底层底座的作用
人工智能·深度学习·生成对抗网络·自然语言处理·知识图谱·agi
计算机科研狗@OUC13 天前
(cvpr26) AIMDepth: Asymmetric Image-Event Mamba for Monocular Depth Estimation
人工智能·深度学习·计算机视觉
β添砖java13 天前
深度学习(22)网络中的网络NiN
人工智能·深度学习
Kobebryant-Manba13 天前
深度学习时候d2l报错和使用问题
人工智能·深度学习
zhangfeng113313 天前
deepspeed zero3 结合 llamafactory 微调 ,save_only_model: true 导致保存时候出错
开发语言·python·深度学习
大模型最新论文速读13 天前
06-16 · LLM 最新论文速览
论文阅读·人工智能·深度学习·机器学习·自然语言处理