在Matlab 2022a中,你可以使用内置的regress函数来计算多输出回归模型的R方值。以下是添加R方评估模型的代码示例:

% 步骤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];

actual = testOutputs;
R2 = zeros(1, 4);
for i = 1:4
    R2(i) = regress(actual(:, i), predictions(:, i));
end

disp(R2);

在上述代码中,我们首先使用TreeBagger函数训练随机森林回归模型,并将其存储在TreeMdl1TreeMdl4变量中。然后,我们使用训练好的模型对测试集特征testFeatures进行预测,并将预测结果存储在predictions1predictions4中。

接下来,我们使用regress函数来计算每个输出的R方值。在每个循环中,我们将实际输出值actual的对应列与预测值predictions的对应列进行回归计算,得到R方值,并将其存储在R2向量中。

最后,使用disp函数打印出计算得到的R方值。

请注意,这段代码假设testOutputspredictions的维度都是(N,4),其中N是测试样本的数量。如果实际情况不符,你可能需要根据数据的实际维度进行调整。


原文地址: https://www.cveoy.top/t/topic/QII 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录