pytorch mnist视觉应用程序,用于使用cainvas的tinyml设备

    科技2026-09-04  5

    Digit recognition is a procedure adopted by machines to recognize handwritten digits. In the real-world online recognition of digits is done by machine to recognize bank cheque amounts, evaluating numbers filled up hands-on various documents like tax forms, and so on.

    数字识别是机器采用的识别手写数字的过程。 在现实世界中,数字的在线识别是由机器完成的,以识别银行支票金额,评估填写在各种文件(如税单)上的数字,等等。

    A difficulty in the case of handwriting digits is that the style, size, width, and orientation of every digit is different every time, which differs from person to person. Thus it is a hard task for machines to recognize handwritten digits perfectly every time. However, the recent progress in machine learning makes it easier for machines to recognize handwritten digits of various sizes, width, and orientation.

    手写数字的一个难题是每个数字的样式,大小,宽度和方向每次都不同,这因人而异。 因此,对于机器而言,每次都能完美地识别手写数字是一项艰巨的任务。 但是,机器学习的最新进展使机器更容易识别各种大小,宽度和方向的手写数字。

    In this article, we will try to develop a handwritten digit recognization App using the MNIST dataset and Pytorch framework. Basically we will be designing a Neural network in the Pytorch framework using the MNIST dataset and will finally compile it in deepC, to finally get our desired output.

    在本文中,我们将尝试使用MNIST数据集和Pytorch框架开发手写数字识别App。 基本上,我们将使用MNIST数据集在Pytorch框架中设计一个神经网络,并最终在deepC中对其进行编译,以最终获得所需的输出。

    MNIST数据集 (The MNIST Dataset)

    The MNIST (Modified National Institute of Standards and Technology) dataset contains 60,000 images in the training set and 10,000 images in the testing dataset, both images having 10 digits ranging from 0–9. The handwritten digits are placed in 28*28 matrix in the form of images, where each cell contains greyscale pixel values.

    MNIST(美国国家标准技术研究院)数据集包含训练集中的60,000张图像和测试数据集中的10,000张图像,两个图像的10位数字范围为0–9。 手写数字以图像形式放置在28 * 28矩阵中,其中每个单元格均包含灰度像素值。

    下载数据集 (Download Dataset)

    !wget -N 'https://cainvas-static.s3.amazonaws.com/media/user_data/cainvas-admin/MNIST.zip' !unzip -o MNIST.zip

    划分数据集(Divide Dataset)

    MNIST_dataset = 'MNIST/data' train = MNIST(MNIST_dataset, train=True, download=True, transform=transforms.Compose([ transforms.ToTensor(), # ToTensor does min-max normalization. ]), ) test = MNIST(MNIST_dataset, train=False, download=True, transform=transforms.Compose([ transforms.ToTensor(), # ToTensor does min-max normalization. ]), ) # Create DataLoader dataloader_args = dict(shuffle=True, batch_size=256,num_workers=4, pin_memory=True) if cuda else dict(shuffle=True, batch_size=64) train_loader = dataloader.DataLoader(train, **dataloader_args) test_loader = dataloader.DataLoader(test, **dataloader_args)

    检查数据集(Inspect Dataset)

    train_data = train.train_data train_data = train.transform(train_data.numpy()) # print(train_data[:, 0, :].shape) # for px in train_data[:, 0, :]: # print(px, ' ') print('[Train]') print(' - Numpy Shape:', train.train_data.cpu().numpy().shape) print(' - Tensor Shape:', train.train_data.size()) print(' - min:', torch.min(train_data)) print(' - max:', torch.max(train_data)) print(' - mean:', torch.mean(train_data)) print(' - std:', torch.std(train_data)) print(' - var:', torch.var(train_data))

    设计一个NN(神经网络)模型(Designing a NN (Neural network) Model)

    class Model(nn.Module): def __init__(self): batch_size = 100 super(Model, self).__init__() self.fc = nn.Linear(784, batch_size) self.fc2 = nn.Linear(batch_size, 10) def forward(self, x): x = x.view((-1, 784)) h = F.relu(self.fc(x)) h = self.fc2(h) return F.log_softmax(h) model = Model() if cuda: model.cuda() # CUDA! optimizer = optim.Adam(model.parameters(), lr=1e-3)

    The NN model consists of one input layer, two fully connected hidden layers, and one output layer. The first hidden layer can take 784 values from the input layer but passes 100 values out of it (where batch_size =100), whereas the second hidden layer takes 100 input values from the first hidden layer and passes 10 numeric values(0–9) which are finally stored in the output layer. The softmax activation function brings out the max probable value which is stored in the actual output and displays it.

    NN模型由一个输入层,两个完全连接的隐藏层和一个输出层组成。 第一个隐藏层可以从输入层获取784个值,但从其中获取100个值(其中batch_size = 100),而第二个隐藏层从第一个隐藏层获取100个输入值,并传递10个数值(0–9)最终存储在输出层中。 softmax激活功能会导出存储在实际输出中的最大可能值并显示出来。

    The loss function is used to find the difference between the desired output and the obtained output. The Neutral network is trained for 10 epochs, and finally, we obtain 97.7100% Test Accuracy!

    损失函数用于查找所需输出与获得的输出之间的差异。 中性网络训练了10个纪元,最后,我们获得了97.7100%的测试准确度!

    用deepC编译: (Compiling with deepC:)

    To bring the saved model on MCU, install deepC — an open-source, vendor-independent deep learning library cum compiler and inference framework, for microcomputers and micro-controllers.

    要将保存的模型带入MCU,请安装deepC —适用于微型计算机和微控制器的开源,独立于供应商的深度学习库以及编译器和推理框架。

    !deepCC mnist_model.onnx

    Here’s the link to the complete notebook:https://cainvas.ai-tech.systems/use-cases/pytorch-mnist-vision-app/

    这是完整笔记本的链接: https : //cainvas.ai-tech.systems/use-cases/pytorch-mnist-vision-app/

    翻译自: https://medium.com/ai-techsystems/pytorch-mnist-vision-app-for-tinyml-devices-using-cainvas-bfaa458bd24f

    Processed: 0.008, SQL: 9