clc;clear;
data = readtable('C:\Users\Administrator\Desktop\RFRtest.csv');
x = data(:,2:end-1);
y = data(:,end);
% 将数据集按30%分成训练集和测试集
cv = cvpartition(size(x,1),'HoldOut',0.3);
idx = cv.test;
Xtrain = x(~idx,:);
Ytrain = y(~idx,:);
Xtest = x(idx,:);
Ytest = y(idx,:);
% 使用TreeBagger函数训练随机森林分类器
ntrees = 100; % 树的数量
B = TreeBagger(ntrees,Xtrain,Ytrain,'Method','regression','OOBPrediction','On','OOBPredictorImportance','on');
Ypred =predict(B,Xtest);Ytest = table2array(Ytest);
% 评估模型性能
rmse = sqrt(mean((Ytest - Ypred).^2));
r_squared = corrcoef(Ytest, Ypred).^2;
% 显示评估结果
disp(['均方根误差(RMSE): ', num2str(rmse)]);
disp(['R²值: ', num2str(r_squared(1, 2))]);
importance = B.OOBPermutedPredictorDeltaError; % 重要性
disp(['特征重要性:',num2str(importance)]);
% 绘制测试集预测图
figure
scatter(Ytest, Ypred)
hold on
plot(xlim, ylim, '--k')
xlabel('测试集真实值');
ylabel('测试集预测值');
xlim([min(Ytest) max(Ytest)])
ylim([min(Ypred) max(Ypred)])
title(['测试集预测值 vs. 测试集真实值, R^2 = ', num2str(r_squared(1, 2))]);
08-28
790
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)