使用PIL将mnist手写数字显示(《深度学习入门:基于Python的理论与实现》实践笔记)

使用PIL将mnist手写数字显示(《深度学习入门:基于Python的理论与实现》实践笔记)

一、将mnist数据集导入numpy数组

这里使用load_mnist函数将mnist数据集导入numpy数组,这个函数可以看本人的另一篇文章:将MNIST手写数字数据集导入NumPy数组(《深度学习入门:基于Python的理论与实现》实践笔记)

(x_train, t_train), (x_test, t_test) = load_mnist(flatten=True, normalize=False)

二、取其中一张图片数据数组传入fromarray函数并显示图片

img = x_train[5438]  # 数据集中第5438张图片
label = t_train[5438]  # 数据集中第5438张图片的数字
print(label)  # 输出图片的数字
img = img.reshape(28, 28)  # 转变为28×28的数组
pil_img = PIL.Image.fromarray(np.uint8(img))  # fromarray函数将array转换成image
pil_img.show()  # 显示图片
  • fromarray函数可以将array数组转化为image图片

三、完整程序(可直接运行)

import urllib.request
import gzip
import numpy as np
import os
import pickle
from PIL import Image


def load_mnist(normalize=True, flatten=True, one_hot_label=False):
    # 用dataset字典保存由4个文件读取得到的np数组
    dataset = {}
    # 若不存在pkl文件,下载文件导入numpy数组,并生成pkl文件
    if not os.path.exists('mnist.pkl'):
        # MNIST数据集的4个文件
        key_file = {
            'train_img': 'train-images-idx3-ubyte.gz', 'train_label': 'train-labels-idx1-ubyte.gz',
            'test_img': 't10k-images-idx3-ubyte.gz', 'test_label': 't10k-labels-idx1-ubyte.gz'
        }
        # 下载文件并导入numpy数组
        for _ in key_file.keys():
            print('Downloading ' + key_file[_] + '...')
            urllib.request.urlretrieve('http://yann.lecun.com/exdb/mnist/' + key_file[_], key_file[_])  # 下载文件
            print('Download finished!')
            # 用二进制只读方式打开.gz文件
            with gzip.open(key_file[_], 'rb') as f:
                # img文件前16个字节不是img数据,跳过读取;label文件前8个不是label数据,跳过读取
                dataset[_] = np.frombuffer(f.read(), np.uint8,
                                           offset=16 if _ == 'train_img' or _ == 'test_img' else 8)
                if _ == 'train_img' or _ == 'test_img':
                    dataset[_] = dataset[_].reshape(-1, 1, 28, 28)
        # 生成mnist.pkl
        print('Creating pickle file ...')
        with open('mnist.pkl', 'wb') as f:
            pickle.dump(dataset, f, -1)
        print('Create finished!')
    # 若存在pkl文件,把pkl文件内容导入numpy数组
    else:
        with open('mnist.pkl', 'rb') as f:
            dataset = pickle.load(f)
    # 标准化处理
    if normalize:
        for _ in ('train_img', 'test_img'):
            dataset[_] = dataset[_].astype(np.float32) / 255.0
    # one_hot_label处理
    if one_hot_label:
        for _ in ('train_label', 'test_label'):
            t = np.zeros((dataset[_].size, 10))
            for idx, row in enumerate(t):
                row[dataset[_][idx]] = 1
            dataset[_] = t
    # 展平处理
    if flatten:
        for _ in ('train_img', 'test_img'):
            dataset[_] = dataset[_].reshape(-1, 784)
    # 返回np数组
    return (dataset['train_img'], dataset['train_label']), (dataset['test_img'], dataset['test_label'])


if __name__ == '__main__':
    (x_train, t_train), (x_test, t_test) = load_mnist(flatten=True, normalize=False)
    img = x_train[5438]  # 数据集中第5438张图片
    label = t_train[5438]  # 数据集中第5438张图片的数字
    print(label)  # 输出图片的数字
    img = img.reshape(28, 28)  # 转变为28×28的数组
    pil_img = Image.fromarray(np.uint8(img))  # fromarray函数将array转换成image
    pil_img.show()  # 显示图片


本实例来自于,由[日]斋藤康毅所著的《深度学习入门:基于Python的理论与实现》。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,手写数字识别是一个非常经典的图像分类问题,MNIST数据集是一个非常常用的用于手写数字识别的数据集。那么我们可以通过构建一个基于神经网络的模型来实现手写数字的识别。 首先,我们需要加载MNIST数据集,并对数据进行预处理。MNIST数据集中包含了60000张训练图片和10000张测试图片,每张图片都是28*28的灰度图像。我们可以使用PyTorch中的torchvision来加载MNIST数据集: ```python import torch import torchvision import torchvision.transforms as transforms # 定义数据预处理方式 transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) # 加载训练集 trainset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True, num_workers=2) # 加载测试集 testset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform) testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=False, num_workers=2) ``` 在加载数据集时,我们使用了一个叫做transform的参数,它是用来定义数据预处理的方式的。在这里,我们使用了ToTensor()函数将图片从PIL类型转换成PyTorch中的Tensor类型,并使用了Normalize()函数对数据进行归一化处理,其中(0.1307,)和(0.3081,)是MNIST数据集中所有像素点的均值和标准差。 接下来,我们可以定义一个基于神经网络的模型。在这里,我们使用了一个包含两个隐藏层的全连接神经网络,每个隐藏层包含256个神经元,输出层包含10个神经元,分别代表数字0到9。我们使用ReLU作为激活函数,并使用交叉熵作为损失函数。 ```python import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fc1 = nn.Linear(784, 256) self.fc2 = nn.Linear(256, 256) self.fc3 = nn.Linear(256, 10) def forward(self, x): x = x.view(-1, 784) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x net = Net() ``` 最后,我们可以使用PyTorch中的优化器和损失函数对模型进行训练,并在测试集上进行测试: ```python import torch.optim as optim criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) # 训练模型 for epoch in range(10): # 训练数据集10次 running_loss = 0.0 for i, data in enumerate(trainloader, 0): inputs, labels = data optimizer.zero_grad() outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() running_loss += loss.item() if i % 100 == 99: # 每100个batch输出一次loss print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 100)) running_loss = 0.0 print('Finished Training') # 在测试集上测试模型的准确率 correct = 0 total = 0 with torch.no_grad(): for data in testloader: images, labels = data outputs = net(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy of the network on the 10000 test images: %d %%' % ( 100 * correct / total)) ``` 通过运行上述代码,我们可以得到一个在测试集上准确率约为98%的手写数字识别模型。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值