機器學習 MATLAB讀取mnist資料庫

2021-07-11 11:13:26 字數 2700 閱讀 1808

最近要做《優化理論基礎》的課程大作業,需要用到mnist這個手寫識別資料庫,在網上查了一下如何使用,分享在這裡,以饗讀者。

mnist是紐約大學(nyu)yann lecun在上個世紀90年代做的乙個關於手寫數字識別的資料庫。該資料庫提出的motivation是為了解決美國郵政zip code機器識別的問題。經過十幾年的發展,目前手寫數字識別的識別率已經高達99%+,真正地做到了商業化。

在yann lecun教授主頁上有對mnist資料集的簡單說明。首先明確一下,資料集中有哪幾個檔案。

train-images-idx3-ubyte.gz: 訓練資料集資料

train-labels-idx1-ubyte.gz: 訓練資料集標籤

t10k-images-idx3-ubyte.gz: 測試資料集資料

t10k-labels-idx1-ubyte.gz: 測試資料集標籤

下面說明如何使用mnist資料庫:

本文參考了史丹福大學andrew ng教授的課件,通過loadmnistimages.m和loadmnistlabels.m兩個檔案讀取mnist資料集。

loadmnistimages.m

function

images = loadmnistimages

(filename)

%loadmnistimages returns a 28x28x[number of mnist images] matrix containing

%the raw mnist images

fp = fopen(filename, 'rb');

assert(fp ~= -1, ['could not open ', filename, '']);

magic = fread(fp, 1, 'int32', 0, 'ieee-be');

assert(magic == 2051, ['bad magic number in ', filename, '']);

numimages = fread(fp, 1, 'int32', 0, 'ieee-be');

numrows = fread(fp, 1, 'int32', 0, 'ieee-be');

numcols = fread(fp, 1, 'int32', 0, 'ieee-be');

images = fread(fp, inf, 'unsigned char');

images = reshape(images, numcols, numrows, numimages);

images = permute(images,[2

13]);

fclose(fp);

% reshape to #pixels x #examples

images = reshape(images, size(images, 1) * size(images, 2), size(images, 3));

% convert to double and rescale to [0,1]

images = double(images) / 255;

end

loadmnistlabels.m

function labels = loadmnistlabels(filename)

%loadmnistlabels returns a [number of mnist images]x1 matrix containing

%the labels for the mnist images

fp = fopen(filename, 'rb');

assert(fp ~= -1, ['could

notopen ', filename, '']);

magic = fread(fp, 1, 'int32', 0, 'ieee-be');

assert(magic == 2049, ['bad magic number in ', filename, '']);

numlabels = fread(fp, 1, 'int32', 0, 'ieee-be');

labels = fread(fp, inf, 'unsigned char');

assert(size(labels,1) == numlabels, 'mismatch

inlabel count');

fclose(fp);

end

可以看到,上述兩個指令碼的核心都是,先通過fopen得到檔案控制代碼fid,在偏移得到魔數(magic)以及一些其他的資訊,最終得到所有的資料,並將資料reshape到相應的維度(都是28x28大小的)。

在mnist資料庫中,lecun教授已經對該資料庫進行了一定的說明,如下所示:

可見,我們的檔案是乙個binary的檔案,在第乙個偏移是魔數,我猜測作用應該是為了作校驗。其中label是2049,而image是2051。之後的偏移量是數、行數、列數。之後就是pixel的值了。pixel的值是0~255的0。0(白色)作為背景、255(黑色)作為前景。

本文介紹了如何在matlab中使用,你學會了麼?

機器學習matlab

rain data是訓練特徵資料,train label是分類標籤。predict label是 的標籤。matlab訓練資料,得到語義標籤向量 scores 概率輸出 1.邏輯回歸 多項式multinomial logistic regression factor mnrfit train dat...

matlab機器學習庫

knn fitcknn meas,species,numneighbors 5 cvmdl crossval knn kloss kfoldloss cvmdl predict knn,ones 1,size meas,2 latent 特徵值 從大到小 score特徵向量 coeff,score,...

tensorflow教程學習三深入MNIST

載入資料 from tensorflow.examples.tutorials.mnist import input data mnist input data.read data sets mnist data one hot true 我們使用interactivesession類可以更加靈活地...