ver0.83--readMNIST.m

来源:互联网 发布:剑倚天下魔刃进阶数据 编辑:程序博客网 时间:2024/05/16 09:39
%关于MNIST手写图像数据库的读取。%输入:%id - 图像的28x28大小单元格数组;%n - 要处理的图像数;%labels - 对应于图像的标签单元格数组;%rand_on - 参数,定义是否需要随机选取一对图像/标签%输出:% I - 训练图像的28x28大小单元阵列%labels - 训练集的标签矢量(真实数字)%I_test - 测试图像的28x28大小单元格数组%labels_test - 测试集的标签向量(真实数字)function [I,labels,I_test,labels_test] = readMNIST(num)%检查我们是否有MNIST数据集path = './MNIST/train-images.idx3-ubyte';if(~exist(path,'file'))    error('Training set of MNIST not found. Please download it from http://yann.lecun.com/exdb/mnist/ and put to ./MNIST folder');endfid = fopen(path,'r','b');  %big-endianmagicNum = fread(fid,1,'int32');    % “fread”以二进制形式,从文件读出数据。if(magicNum~=2051)     display('Error: cant find magic number');    return;endimgNum = fread(fid,1,'int32');  %Number of imagesrowSz = fread(fid,1,'int32');   %Image heightcolSz = fread(fid,1,'int32');   %Image widthif(num<imgNum)     imgNum=num; endfor k=1:imgNum    I{k} = uint8(fread(fid,[rowSz colSz],'uchar'));%[M,N]:读出N个数据,构成列向量,填入M*N矩阵endfclose(fid);%============Loading labelspath = './MNIST/train-labels.idx1-ubyte';if(~exist(path,'file'))    error('Training labels of MNIST not found. Please download it from http://yann.lecun.com/exdb/mnist/ and put to ./MNIST folder');endfid = fopen(path,'r','b');  %big-endianmagicNum = fread(fid,1,'int32');    %Magic numberif(magicNum~=2049)     display('Error: cant find magic number');    return;enditmNum = fread(fid,1,'int32');  %Number of labelsif(num<itmNum)     itmNum=num; endlabels = uint8(fread(fid,itmNum,'uint8'));   %Load all labelsfclose(fid);%============All the same for test setpath = './MNIST/t10k-images.idx';if(~exist(path,'file'))    error('Test images of MNIST not found. Please download it from http://yann.lecun.com/exdb/mnist/ and put to ./MNIST folder');endfid = fopen(path,'r','b');  magicNum = fread(fid,1,'int32');    if(magicNum~=2051)     display('Error: cant find magic number');    return;endimgNum = fread(fid,1,'int32');  rowSz = fread(fid,1,'int32');   colSz = fread(fid,1,'int32');   if(num<imgNum)     imgNum=num; endfor k=1:imgNum    I_test{k} = uint8(fread(fid,[rowSz colSz],'uchar'));endfclose(fid);%============Test labelspath = './MNIST/t10k-labels.idx1-ubyte';if(~exist(path,'file'))    error('Test labels of MNIST not found. Please download it from http://yann.lecun.com/exdb/mnist/ and put to ./MNIST folder');endfid = fopen(path,'r','b');  magicNum = fread(fid,1,'int32');    if(magicNum~=2049)     display('Error: cant find magic number');    return;enditmNum = fread(fid,1,'int32');  if(num<itmNum)     itmNum=num; endlabels_test = uint8(fread(fid,itmNum,'uint8'));   fclose(fid);

如果输入为1000,就是1000张用于训练,1000张用于测试??

0 0