朴素贝叶斯分类器matlab花卉
时间: 2023-11-29 16:47:16 浏览: 99
以下是使用朴素贝叶斯分类器在MATLAB中对花卉数据集进行分类的示例代码:
```matlab
% 加载数据集
load fisheriris
% 将数据集分为训练集和测试集
[trainInd,testInd] = dividerand(size(meas,1),0.7,0.3);
trainData = meas(trainInd,:);
trainLabels = species(trainInd);
testData = meas(testInd,:);
testLabels = species(testInd);
% 训练朴素贝叶斯分类器
nb = fitcnb(trainData,trainLabels);
% 对测试集进行分类
predictedLabels = predict(nb,testData);
% 计算分类准确率
accuracy = sum(predictedLabels == testLabels)/numel(testLabels)
% 绘制决策边界
figure;
gscatter(meas(:,1),meas(:,2),species,'rgb','osd');
hold on;
h = gca;
xLimits = h.XLim;
yLimits = h.YLim;
[X,Y] = meshgrid(linspace(xLimits(1),xLimits(2),200),linspace(yLimits(1),yLimits(2),200));[~,scores] = predict(nb,[X(:),Y(:)]);
contour(X,Y,reshape(scores(:,2),size(X)),[0.5,0.5],'k');
title('Decision Boundary');
xlabel('Sepal Length');
ylabel('Sepal Width');
```
该代码使用了MATLAB内置的`fitcnb`函数来训练朴素贝叶斯分类器,并使用`predict`函数对测试集进行分类。最后,使用`gscatter`和`contour`函数绘制了决策边界。
阅读全文