画像分類で交差検証による誤分類率導出について
1 view (last 30 days)
Show older comments
画像の分類で,以下のコードを使用して,交差検証を行い,誤分類率を出そうとしています。
imds = imageDatastore('crossval_data', ...
'IncludeSubfolders',true, ...
'LabelSource','foldernames');
figure;
perm = randperm(220,22);
for i = 1:20
subplot(4,5,i);
imshow(imds.Files{perm(i)});
end
labelCount = countEachLabel(imds);
img = readimage(imds,1);
size(img)
numTrainFiles = 100;
[imdsTrain,imdsValidation] = splitEachLabel(imds,numTrainFiles,'randomize');
%% ダミーのトレーニングインデックスを生成
X = (1:imds.numpartitions)';
y = imds.Labels;
%% 交差検定にCNNの予測ラベル関数のポインタを渡す
cp = cvpartition(y,'k',2); % Stratified cross-validation
mcr = crossval('mcr',X,y,'Predfun',@(xtrain,ytrain,xtest)myCNNPredict(xtrain,ytrain,xtest,imds),'partition',cp);
%% CNNを学習し、予測ラベルを出力する関数
function ypred = myCNNPredict(xtrain,ytrain,xtest,imds)
% 結果が一意になるように乱数シードをデフォルト値に設定
rng('default');
% ダミーの変数ベクトルを受けてimageDatastoreを学習用とテスト用に分割
imdsTrain = imageDatastore(imds.Files(xtrain));
imdsTrain.Labels = ytrain;
imdsValidation = imageDatastore(imds.Files(xtest));
% レイヤーの設定
layers = [
imageInputLayer([28 28 1],'Name','input')
convolution2dLayer(3,8,'Padding','same','Name','conv1')
batchNormalizationLayer('Name','BN1')
reluLayer('Name','relu1')
crossChannelNormalizationLayer(5)
maxPooling2dLayer(2,'Stride',2,'Name','pool1')
convolution2dLayer(3,16,'Padding','same','Name','conv2')
batchNormalizationLayer('Name','BN2')
reluLayer('Name','relu2')
crossChannelNormalizationLayer(5)
maxPooling2dLayer(2,'Stride',2,'Name','pool2')
convolution2dLayer(3,32,'Padding','same','Name','conv3')
batchNormalizationLayer('Name','BN3')
reluLayer('Name','relu3')
dropoutLayer('probability',0.5,'Name','drop6')
fullyConnectedLayer(2,'Name','fc')
softmaxLayer('Name','softmax')
classificationLayer('Name','classoutput')];
options = trainingOptions('sgdm', ...
'InitialLearnRate',0.01, ...
'MaxEpochs',5, ...
'Shuffle','every-epoch', ...
'Verbose',false);
net2 = trainNetwork(imdsTrain,layers,options);
ypred = classify(net2,imdsValidation);
save net2
end
最初はうまく誤分類率が出ていたのですが,突然以下のようなエラーが出てしまい,誤分類率が出なくなりました。
関数としてスクリプト crossval を実行しようとしています:
C:\Users\naots\OneDrive\デスクトップ\AI_exp\crossval.m
エラー: crossval (line 20)
mcr = crossval('mcr',X,y,'Predfun',@(xtrain,ytrain,xtest)myCNNPredict(xtrain,ytrain,xtest,imds),'partition',cp);
どこか間違っているとこがあれば,教えていただけると幸いです。
よろしくお願い致します。
2 Comments
Accepted Answer
Kenta
on 30 Aug 2020
こんにちは、コメントのほう、返信いただきありがとうございます。MATLABの関数と、自分で用意したファイルが同じだと、うまく行かない場合が多くあるので、crossval_exp1などと、うまく整理できるようにタイトルを変えると良いと思います。また、変数でもおなじことで、例えばmeanという関数があるので、meanという名前の変数は作成しない方が無難です。参考になれば幸いです。
More Answers (0)
See Also
Categories
Find more on イメージを使用した深層学習 in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!