随机森林matlab代码
时间: 2023-10-30 19:06:43 浏览: 44
下面是一个简单的随机森林 Matlab 代码示例:
```matlab
% 加载数据
load fisheriris;
% 随机打乱数据顺序
rng(1);
randomOrder = randperm(size(meas,1));
meas = meas(randomOrder,:);
species = species(randomOrder);
% 将数据分为训练集和测试集
trainIndices = 1:100;
testIndices = 101:150;
trainData = meas(trainIndices,:);
trainLabels = species(trainIndices);
testData = meas(testIndices,:);
testLabels = species(testIndices);
% 训练随机森林模型
numTrees = 50;
model = TreeBagger(numTrees, trainData, trainLabels);
% 预测测试集数据
predictedLabels = predict(model, testData);
% 计算分类准确率
correctPredictions = strcmp(predictedLabels, testLabels);
accuracy = sum(correctPredictions)/length(correctPredictions);
disp(['分类准确率:', num2str(accuracy*100), '%']);
```
该代码使用了 Fisher's Iris 数据集进行训练和测试,并使用了 Matlab 内置函数 `TreeBagger` 来训练随机森林模型。在训练完成后,代码使用该模型来预测测试集数据,并计算分类准确率。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)