MATLAB 中 随机森林分类器、决策树分类器、KNN、贝叶斯分类器的分类函数是什么,分别如何进行二分类,给出实例代码
时间: 2024-02-02 13:04:20 浏览: 81
MATLAB 中随机森林分类器、决策树分类器、KNN、贝叶斯分类器的分类函数如下:
- 随机森林分类器:predict
- 决策树分类器:predict
- KNN:predict
- 贝叶斯分类器:classify
下面分别给出这四种分类器的二分类实例代码:
1. 随机森林分类器
```matlab
% 加载数据集
load fisheriris
X = meas(:,3:4);
Y = species;
% 将标签转换为二分类问题
Y(strcmp(Y, 'setosa')) = 'positive';
Y(~strcmp(Y, 'positive')) = 'negative';
% 划分训练集和测试集
cv = cvpartition(Y, 'HoldOut', 0.3);
Xtrain = X(cv.training,:);
Ytrain = Y(cv.training);
Xtest = X(cv.test,:);
Ytest = Y(cv.test);
% 训练随机森林分类器
t = templateTree('Surrogate','on');
model = fitcensemble(Xtrain, Ytrain, 'Method', 'Bag', 'NumLearningCycles', 100, 'Learners', t);
% 预测测试集
Ypred = predict(model, Xtest);
% 计算分类准确率
accuracy = sum(strcmp(Ypred, Ytest)) / length(Ytest);
```
2. 决策树分类器
```matlab
% 加载数据集
load fisheriris
X = meas(:,3:4);
Y = species;
% 将标签转换为二分类问题
Y(strcmp(Y, 'setosa')) = 'positive';
Y(~strcmp(Y, 'positive')) = 'negative';
% 划分训练集和测试集
cv = cvpartition(Y, 'HoldOut', 0.3);
Xtrain = X(cv.training,:);
Ytrain = Y(cv.training);
Xtest = X(cv.test,:);
Ytest = Y(cv.test);
% 训练决策树分类器
model = fitctree(Xtrain, Ytrain);
% 预测测试集
Ypred = predict(model, Xtest);
% 计算分类准确率
accuracy = sum(strcmp(Ypred, Ytest)) / length(Ytest);
```
3. KNN
```matlab
% 加载数据集
load fisheriris
X = meas(:,3:4);
Y = species;
% 将标签转换为二分类问题
Y(strcmp(Y, 'setosa')) = 'positive';
Y(~strcmp(Y, 'positive')) = 'negative';
% 划分训练集和测试集
cv = cvpartition(Y, 'HoldOut', 0.3);
Xtrain = X(cv.training,:);
Ytrain = Y(cv.training);
Xtest = X(cv.test,:);
Ytest = Y(cv.test);
% 训练KNN分类器
model = fitcknn(Xtrain, Ytrain);
% 预测测试集
Ypred = predict(model, Xtest);
% 计算分类准确率
accuracy = sum(strcmp(Ypred, Ytest)) / length(Ytest);
```
4. 贝叶斯分类器
```matlab
% 加载数据集
load fisheriris
X = meas(:,3:4);
Y = species;
% 将标签转换为二分类问题
Y(strcmp(Y, 'setosa')) = 'positive';
Y(~strcmp(Y, 'positive')) = 'negative';
% 划分训练集和测试集
cv = cvpartition(Y, 'HoldOut', 0.3);
Xtrain = X(cv.training,:);
Ytrain = Y(cv.training);
Xtest = X(cv.test,:);
Ytest = Y(cv.test);
% 训练贝叶斯分类器
model = fitcnb(Xtrain, Ytrain);
% 预测测试集
Ypred = predict(model, Xtest);
% 计算分类准确率
accuracy = sum(strcmp(Ypred, Ytest)) / length(Ytest);
```
阅读全文