clc;clear;
% 1. 定义数据和目标范围(替换为实际数据)
box1 = [-1, -1, 0, 1, 3, 2]; % 盒子1的6个数字
box2 = [1, 1, 2, 2, 3, 3]; % 盒子2的6个数字
box3 = [1, 2, 3, 4, 5, 6]; % 盒子3的6个数字
boxes = {box1, box2, box3}; % 存储所有盒子
target_min = 1; % 目标范围下限
target_max = 7; % 目标范围上限
% 2. 生成所有可能的3个盒子选择方案(共3^3=27种,允许重复)
schemes = [];
for i = 1:3
for j = 1:3
for k = 1:3
schemes = [schemes; i, j, k]; % 每行表示一个方案:[盒子A, 盒子B, 盒子C]
end
end
end
num_schemes = size(schemes, 1);
% 3. 为所有方案生成训练数据(特征+标签)
features = [];
labels = [];
scheme_ids = []; % 记录每个样本属于哪个方案
for s = 1:num_schemes
% 当前方案选择的盒子编号
scheme = schemes(s, :); % 获取当前方案
n = length(scheme); % 关键修复:定义n为当前方案中盒子的数量(此处固定为3)

% 生成该方案下所有数字组合(6×6×6=216种)
grids = cell(1, n); % 现在n已正确定义
for j = 1:n
grids{j} = boxes{scheme(j)};
end
[grid_vars{1:n}] = ndgrid(grids{:}); % 生成网格
combinations = cell2mat(cellfun(@(x) x(:), grid_vars, 'UniformOutput', false));
% 提取特征
sum_feat = sum(combinations, 2); % 特征1:和
prod_feat = prod(combinations, 2); % 特征2:乘积
sq_sum_feat = sum(combinations.^2, 2); % 特征3:平方和
max_feat = max(combinations, [], 2); % 特征4:最大值
min_feat = min(combinations, [], 2); % 特征5:最小值
current_features = [combinations, sum_feat, prod_feat, sq_sum_feat, max_feat, min_feat];
% 生成标签(1=有效,0=无效)
current_labels = (sum_feat >= target_min) & (sum_feat <= target_max);
current_labels = current_labels(:);
% 汇总数据
features = [features; current_features];
labels = [labels; current_labels];
scheme_ids = [scheme_ids; repmat(s, size(combinations, 1), 1)];
end
% 4. 训练随机森林模型
rng(1); % 固定随机种子,保证结果可复现
idx = randperm(size(features, 1));
train_idx = idx(1:round(0.8*length(idx)));
test_idx = idx(round(0.8*length(idx))+1:end);
% 训练模型
model = fitcensemble(features(train_idx, :), labels(train_idx), ...
'Method', 'Bag', ... % 集成方法:装袋
'NumLearningCycles', 50, ... % 50棵决策树
'Learner', 'tree'); % 基学习器:决策树
% 评估模型性能
pred = predict(model, features(test_idx, :));
accuracy = mean(pred == labels(test_idx));
fprintf('模型测试集准确率:%.2f%%\n', accuracy*100);
% 5. 预测每个方案的有效概率,找到最优方案
scheme_probs = zeros(num_schemes, 1);
for s = 1:num_schemes
s_idx = scheme_ids == s;
s_features = features(s_idx, :);
s_pred = predict(model, s_features);
scheme_probs(s) = mean(s_pred);
end
% 6. 输出结果
[max_prob, best_idx] = max(scheme_probs);
best_scheme = schemes(best_idx, :);
fprintf('\n最优方案:选择(盒子%d, 盒子%d, 盒子%d)\n', ...
best_scheme(1), best_scheme(2), best_scheme(3));
fprintf('该方案的有效概率:%.2f%%\n', max_prob*100);
免责声明:本文系网络转载或改编,未找到原创作者,版权归原作者所有。如涉及版权,请联系删