Matlab读取MNIST数据

本文介绍了如何使用Matlab读取和处理MNIST手写数字识别数据集,包括数据下载、数据格式解析以及数据读取与保存的方法。在Windows环境下需要注意文件名的变化,并解释了如何正确读取32位整型数据。
摘要由CSDN通过智能技术生成

mnist database(手写字符识别) 的数据集下载地:http://yann.lecun.com/exdb/mnist/

准备数据

MNIST是在机器学习领域中的一个经典问题。该问题解决的是把28x28像素的灰度手写数字图片识别为相应的数字,其中数字的范围从0到9.

共有四个文件需要下载:

以下是MATLAB读取mnist数据库的示例代码: ```matlab % 读取训练集 train_images_file = 'train-images-idx3-ubyte'; train_labels_file = 'train-labels-idx1-ubyte'; % 读取图像数据 fp = fopen(train_images_file, 'rb'); magic = fread(fp, 1, 'int32', 0, 'ieee-be'); num_images = fread(fp, 1, 'int32', 0, 'ieee-be'); num_rows = fread(fp, 1, 'int32', 0, 'ieee-be'); num_cols = fread(fp, 1, 'int32', 0, 'ieee-be'); images = fread(fp, inf, 'unsigned char'); images = reshape(images, num_rows, num_cols, num_images); images = permute(images, [2 1 3]); fclose(fp); % 读取标签数据 fp = fopen(train_labels_file, 'rb'); magic = fread(fp, 1, 'int32', 0, 'ieee-be'); num_labels = fread(fp, 1, 'int32', 0, 'ieee-be'); labels = fread(fp, inf, 'unsigned char'); fclose(fp); % 显示图像和标签 index = 1; imshow(images(:,:,index)); title(num2str(labels(index))); % 读取测试集 test_images_file = 't10k-images-idx3-ubyte'; test_labels_file = 't10k-labels-idx1-ubyte'; % 读取图像数据 fp = fopen(test_images_file, 'rb'); magic = fread(fp, 1, 'int32', 0, 'ieee-be'); num_images = fread(fp, 1, 'int32', 0, 'ieee-be'); num_rows = fread(fp, 1, 'int32', 0, 'ieee-be'); num_cols = fread(fp, 1, 'int32', 0, 'ieee-be'); images = fread(fp, inf, 'unsigned char'); images = reshape(images, num_rows, num_cols, num_images); images = permute(images, [2 1 3]); fclose(fp); % 读取标签数据 fp = fopen(test_labels_file, 'rb'); magic = fread(fp, 1, 'int32', 0, 'ieee-be'); num_labels = fread(fp, 1, 'int32', 0, 'ieee-be'); labels = fread(fp, inf, 'unsigned char'); fclose(fp); % 显示图像和标签 index = 1; imshow(images(:,:,index)); title(num2str(labels(index))); ``` 在这个示例中,我们首先读取训练集和测试集的图像数据和标签数据。然后,我们使用`imshow`函数显示了第一张图像和它的标签。需要注意的是,MNIST数据库中的图像数据是28x28的灰度图像,因此需要使用`permute`函数将它们的维度从[行,列,图像数]转换为[列,行,图像数]。
评论 36
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值