% 步骤1:加载和准备数据
% 这里使用MATLAB自带的图像分类数据集
imds = imageDatastore('C:\path\to\your\image\dataset', ...
'IncludeSubfolders',true, 'LabelSource','foldernames');
% 步骤2:加载预训练的CNN模型
net = alexnet;
% 步骤3:分割数据集为训练集和测试集
[imdsTrain,imdsTest] = splitEachLabel(imds,0.7,'randomized');
% 步骤4:定义训练选项
options = trainingOptions('sgdm', ...
'MiniBatchSize',10, ...
'MaxEpochs',6, ...
'InitialLearnRate',1e-4, ...
'Shuffle','every-epoch', ...
'ValidationData',imdsTest, ...
'ValidationFrequency',30, ...
'Verbose',false, ...
'Plots','training-progress');
% 步骤5:训练模型
net = trainNetwork(imdsTrain,net,options);
% 步骤6:评估模型
YPred = classify(net,imdsTest);
YTest = imdsTest.Labels;
accuracy = sum(YPred == YTest) / numel(YTest);
fprintf('测试集准确率: %.2f%%\n', accuracy * 100);
% 步骤7:使用模型进行预测
% 你可以加载新图像并使用模型来进行分类
% 示例代码:
% newImage = imread('path\to\new\image.jpg');
% predictedLabel = classify(net, newImage);
% 步骤8:保存和部署模型(如果需要)
% 如果你满意模型的性能,你可以保存模型并部署到不同的应用程序中
% 释放不再需要的资源
clear imds imdsTrain imdsTest net options YPred YTest accuracy;