matlab做随机森林
时间: 2023-07-20 17:39:29 浏览: 119
在MATLAB中,可以使用TreeBagger函数来实现随机森林算法。下面是一个简单的示例代码:
首先,准备训练和测试数据:
```matlab
load fisheriris
% 随机排列数据
rng(1); % 设置随机数种子,使结果可重复
idx = randperm(size(meas,1));
meas = meas(idx,:);
species = species(idx);
% 划分训练和测试集
numObservations = size(meas,1);
numTraining = floor(0.7*numObservations);
trainingIdx = 1:numTraining;
testIdx = (numTraining+1):numObservations;
```
然后,使用TreeBagger函数训练随机森林模型:
```matlab
numTrees = 50; % 森林中树的数量
Mdl = TreeBagger(numTrees, meas(trainingIdx,:), species(trainingIdx), 'Method', 'classification');
```
接下来,使用predict方法进行预测:
```matlab
predictedSpecies = predict(Mdl, meas(testIdx,:));
```
最后,计算分类准确率:
```matlab
accuracy = sum(strcmp(predictedSpecies, species(testIdx)))/numel(testIdx);
disp(['Classification accuracy: ' num2str(accuracy*100) '%']);
```
完整代码如下:
```matlab
load fisheriris
% 随机排列数据
rng(1); % 设置随机数种子,使结果可重复
idx = randperm(size(meas,1));
meas = meas(idx,:);
species = species(idx);
% 划分训练和测试集
numObservations = size(meas,1);
numTraining = floor(0.7*numObservations);
trainingIdx = 1:numTraining;
testIdx = (numTraining+1):numObservations;
% 训练随机森林模型
numTrees = 50; % 森林中树的数量
Mdl = TreeBagger(numTrees, meas(trainingIdx,:), species(trainingIdx), 'Method', 'classification');
% 预测
predictedSpecies = predict(Mdl, meas(testIdx,:));
% 计算准确率
accuracy = sum(strcmp(predictedSpecies, species(testIdx)))/numel(testIdx);
disp(['Classification accuracy: ' num2str(accuracy*100) '%']);
```
阅读全文