mnist数据处理

import torch as t
import torch.nn as nn
import numpy as np
import os.path
import struct


train_img_dir_ubyte = r'E:\code\LnNet\train-images.idx3-ubyte'
train_label_dir_ubyte = r'E:\code\LnNet\train-labels.idx1-ubyte'
train_size = os.path.getsize(train_img_dir_ubyte)
# 处理MNIST数据 变成矩阵形式
# img_array 每行存储784像素值
# label_array 每个值是对应的图像
with open(train_img_dir_ubyte,'rb') as trf:
    # 不对 是因为魔数 由4字节 数量是3字节 行数 4字节 不统一
    # magic,num,hang,lie = struct.unpack_from('>'+str(12)+'B',trf.read(12))
    magic, img_num, hang, lie = struct.unpack('>IIII',trf.read(16))
    img_csv_data = struct.unpack_from('>'+str(train_size-16)+'B',trf.read())
    img_array = np.array(img_csv_data).astype(np.uint8).reshape(img_num,784)
# print(img_array.shape)
# plt.imshow(img_array[0].reshape(28,28))
# plt.show()
with open(train_label_dir_ubyte,'rb') as tb:
    magic,label_num = struct.unpack('>II',tb.read(8))
    label = struct.unpack_from('>'+str(os.path.getsize(train_label_dir_ubyte)-8)+'B'
                               ,tb.read())
    label_array = np.array(label).astype(np.uint8).reshape(-1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值