分层采样MATLAB程序怎么写
时间: 2023-10-02 09:12:13 浏览: 84
在MATLAB中,可以使用 `datasample` 函数来进行分层采样。具体步骤如下:
1. 读取数据集,将数据集划分为若干个层级,每个层级包含相同的标签或特征。
2. 对于每个层级,使用 `datasample` 函数进行采样。该函数需要指定采样的数据集、采样的数量和是否有放回采样等参数。
3. 将每个层级的采样结果合并为最终的采样数据集。
以下是一个简单的分层采样MATLAB程序示例:
```matlab
% 读取数据集
data = readtable('data.csv');
% 根据标签划分为不同的层级
labels = unique(data.Label);
n_layers = length(labels);
layers = cell(1, n_layers);
for i = 1:n_layers
layers{i} = data(data.Label == labels(i), :);
end
% 对每个层级进行采样
sampled_data = [];
sample_ratio = 0.1; % 采样比例
for i = 1:n_layers
layer_data = layers{i};
n_samples = round(height(layer_data) * sample_ratio);
sampled_layer_data = datasample(layer_data, n_samples, 'Replace', false);
sampled_data = [sampled_data; sampled_layer_data];
end
% 输出采样结果
writetable(sampled_data, 'sampled_data.csv');
```
在上述示例中,首先读取了一个数据集,并将其根据标签划分为不同的层级。然后对于每个层级,使用 `datasample` 函数进行采样,最后将每个层级的采样结果合并为最终的采样数据集。