2016-01-06 48 views
1

我已經通過提供的代碼cnn_mnist訓練了cnn。在那之後,我tryed對圖像進行分類,但我不明白爲什麼我下面的代碼後得到這個錯誤:如何使用MatConvNet中使用cnn_mnist示例訓練的網絡?

[net, info] = cnn_mnist 
net = 
    layers: {1x8 cell} 
info = 
    train: [1x1 struct] 
     val: [1x1 struct] 
f=fopen(fullfile('.\data\mnist\', 't10k-images-idx3-ubyte'),'r') ; 
x2=fread(f,inf,'uint8'); 
fclose(f) ; 
x2=permute(reshape(x2(17:end),28,28,10e3),[2 1 3]) ; 
im = x2(:,:,1); 
im = single(im); 
res = vl_simplenn(net,im); 
Reference to non-existent field 'class'. 
Error in vl_simplenn (line 163) 
     res(i+1).x = vl_nnsoftmaxloss(res(i).x, l.class) ; 

回答

2

我不知道爲什麼你的代碼將無法運行。我相信問題出在你的最後一層。默認情況下它由softmaxloss定義,您應該將其更改爲softmax。嘗試調用vl_simplenn之前添加此行:

net.layers{end}.type = 'softmax'; 

反正試試這個代碼爲我的作品(你應該從主MatConvNet文件夾中運行它):

%%%%%%%%%%% run this lines only once at matlab startup 
run matlab/vl_compilenn 
run matlab/vl_setupnn 
%%%%%%%%%%% 

load('examples\mnist\data\mnist-bnorm\net-epoch-20.mat'); % files from training 
net.layers{end}.type = 'softmax'; 
im = imread('Capture.jpg') ; % an image of a handwritten number 
im = rgb2gray(im); 
im_ = single(im) ; % note: 0-255 range 
im_ = imresize(im_, net.meta.inputSize(1:2)+1) ; 
load('examples\mnist\data\mnist-bnorm\imdb.mat') 
im_ = im_ - images.data_mean; 

% run the CNN 
res = vl_simplenn(net, im_) ; 

% show the classification result 
scores = squeeze(gather(res(end).x)) ; 
[bestScore, best] = max(scores) ; 
best = best - 1; % shift the score from 1:10 to 0:9 
figure(1) ; clf ; imshow(im) ; 
title(sprintf('The number is %s, score %.1f%%',... 
net.meta.classes.name{best+1}-1, bestScore * 100)) ; 
0

使用matconvnet-1.0-beta24,二可能出現的問題可能是如下:

  1. 代替res = vl_simplenn(net, im_) ; 使用:

    res = vl_simplenn(net, im_, [], [], 'mode', 'test'); 
    
  2. 用於測試的圖片背景應該是黑色的,手寫的數字應該是白色的。因此,如果您從互聯網下載帶有白色背景和黑色號碼的圖片,請使用:

    im_=255-im_;