层次抽样matlab程序
时间: 2023-08-23 21:47:08 浏览: 106
层次抽样是一种常用的抽样方法,它可以有效地减小样本误差,提高估计精度。在 MATLAB 中,可以使用 `stratifiedSample` 函数进行层次抽样。下面是一个使用 `stratifiedSample` 函数进行层次抽样的示例程序。
```matlab
% 生成示例数据
N = 1000;
X = randn(N, 2);
Y = X(:, 1).^2 + X(:, 2).^2 > 1;
% 层次抽样
n1 = 100;
n2 = 200;
idx1 = find(Y == 0);
idx2 = find(Y == 1);
sampled_idx1 = stratifiedSample(idx1, n1);
sampled_idx2 = stratifiedSample(idx2, n2);
sampled_idx = [sampled_idx1; sampled_idx2];
X_sampled = X(sampled_idx, :);
Y_sampled = Y(sampled_idx);
% 绘制抽样后的数据分布
figure
scatter(X(Y == 0, 1), X(Y == 0, 2), 'b', 'filled')
hold on
scatter(X(Y == 1, 1), X(Y == 1, 2), 'r', 'filled')
scatter(X_sampled(Y_sampled == 0, 1), X_sampled(Y_sampled == 0, 2), 'b', 'o')
scatter(X_sampled(Y_sampled == 1, 1), X_sampled(Y_sampled == 1, 2), 'r', 'o')
legend('Class 0', 'Class 1', 'Sampled Class 0', 'Sampled Class 1', 'Location', 'northwest')
```
运行结果如下图所示,可以看到抽样后的数据分布较为均匀,能够更好地反映原始数据的分布情况。

阅读全文
相关推荐















