1957

无聊蛋疼的1957写的低端博客
随笔 - 214, 文章 - 1, 评论 - 38, 阅读 - 21万
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

python读取mnist

Posted on   1957  阅读(28850)  评论(5编辑  收藏  举报

其实就是python怎么读取binnary file

mnist的结构如下,选取train-images

 

TRAINING SET IMAGE FILE (train-images-idx3-ubyte):

[offset] [type]          [value]          [description] 
0000     32 bit integer  0x00000803(2051) magic number 
0004     32 bit integer  60000            number of images 
0008     32 bit integer  28               number of rows 
0012     32 bit integer  28               number of columns 
0016     unsigned byte   ??               pixel 
0017     unsigned byte   ??               pixel 
........ 
xxxx     unsigned byte   ??               pixel

 

也就是之前我们要读取4个 32 bit integer

 

试过很多方法,觉得最方便的,至少对我来说还是使用

struct.unpack_from()

 

filename = 'train-images.idx3-ubyte'
binfile = open(filename , 'rb')
buf = binfile.read()

 先使用二进制方式把文件都读进来

 

index = 0
magic, numImages , numRows , numColumns = struct.unpack_from('>IIII' , buf , index)
index += struct.calcsize('>IIII')

 然后使用struc.unpack_from

'>IIII'是说使用大端法读取4个unsinged int32

 

然后读取一个图片测试是否读取成功

im = struct.unpack_from('>784B' ,buf, index)
index += struct.calcsize('>784B')
 
im = np.array(im)
im = im.reshape(28,28)
 
fig = plt.figure()
plotwindow = fig.add_subplot(111)
plt.imshow(im , cmap='gray')
plt.show()

 '>784B'的意思就是用大端法读取784个unsigned byte

 

完整代码如下

import numpy as np
import struct
import matplotlib.pyplot as plt
 
filename = 'train-images.idx3-ubyte'
binfile = open(filename , 'rb')
buf = binfile.read()
 
index = 0
magic, numImages , numRows , numColumns = struct.unpack_from('>IIII' , buf , index)
index += struct.calcsize('>IIII')
 
im = struct.unpack_from('>784B' ,buf, index)
index += struct.calcsize('>784B')
 
im = np.array(im)
im = im.reshape(28,28)
 
fig = plt.figure()
plotwindow = fig.add_subplot(111)
plt.imshow(im , cmap='gray')
plt.show()

 只是为了测试是否成功所以只读了一张图片

 

赶脚应该是读对了哈。。。

编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示