Matlab随机森林回归模型构建与评估
% 步骤1:回归准备数据
res = xlsread('位移角性能点预测数据库1.1.xlsx');
% 步骤2:划分数据集
cv = cvpartition(size(res, 1), 'HoldOut', 0.2); % 80% 作为训练集和预测集,20% 作为测试集
trainingData = res(cv.training,:);
trainFeatures = trainingData(:, 1:11);
trainOutputs = trainingData(:, end-3:end);
testData = res(cv.test,:);
testFeatures = testData(:, 1:11);
testOutputs = testData(:, end-3:end);
trainIdx = training(cv);
testIdx = test(cv);
cv2 = cvpartition(sum(trainIdx), 'KFold', 5); % 交叉验证使用的折数
trainData = res(trainIdx, :);
testData = res(testIdx, :);
predictFeatures = double(res(:, 1:11));
% 步骤3:创建随机森林回归模型并进行交叉验证
NumTrees = 400;
nLeaf = 5;
TreeMdl1 = TreeBagger(NumTrees, trainFeatures, trainOutputs(:,1), 'oobprediction', 'on', 'method', 'regression','minleaf', nLeaf);
TreeMdl2 = TreeBagger(NumTrees, trainFeatures, trainOutputs(:,2), 'oobprediction', 'on', 'method', 'regression','minleaf', nLeaf);
TreeMdl3 = TreeBagger(NumTrees, trainFeatures, trainOutputs(:,3), 'oobprediction', 'on', 'method', 'regression','minleaf', nLeaf);
TreeMdl4 = TreeBagger(NumTrees, trainFeatures, trainOutputs(:,4), 'oobprediction', 'on', 'method', 'regression','minleaf', nLeaf);
% 步骤4:预测
predictions1 = predict(TreeMdl1, testFeatures);
predictions2 = predict(TreeMdl2, testFeatures);
predictions3 = predict(TreeMdl3, testFeatures);
predictions4 = predict(TreeMdl4, testFeatures);
predictions = [predictions1, predictions2, predictions3, predictions4];
% 步骤5:使用R方评估模型
actual = testOutputs;
R2 = zeros(1,4);
for i = 1:4
R2(i) = regress(actual(:,i), predictions(:,i));
end
disp('各个输出的R方值:');
disp(R2);
原文地址: https://www.cveoy.top/t/topic/QEN 著作权归作者所有。请勿转载和采集!