等频采样数据
sampling data with equal frequency
我有一个标签向量labels
,其中包含 10 个 class 的 60000 个对象的标签信息(每个 class 有 6000 个样本)。
我需要随机抽取1000个样本,还要保证每个100个class。
我假设您的数据是随机排序的?所以像这样(为了简单起见,我将只使用 3 个 class、1
、2
和 3
):
data = [ones(n,1); ones(n,1)*2; ones(n,1)*3];
data = data(randperm(numel(data)));
所以现在你想要 m*3
个样本,每个 class 个样本有 m
个样本(其中 m <= n
)。最自然的方法是对每个 class 精确 m
个样本不那么严格,只选择 m*3
个样本 uniformly-randomly:
idx = randperm(numel(data));
sample = data(numel(data))
请注意,如果您有统计工具箱,则可以使用 randsample
而不是 randperm
。
但是,如果您必须准确地 m
每个样本,那么应该这样做。请注意,我的目标是获取索引而不是值,因为我认为这更符合您的要求:
classes = unique(data);
k = numel(classes);
idx = false(m*3,1);
for class = 1:k
%// find the element numbers for each element of that class
idxForClass = find(data == classes(class));
%// Shuffle them randomly
idxForClassShuffled = idxForClass(randperm(numel(idxForClass))); %// or numel(n)
%// Pick the first m from the shuffled list
idx(idxForClassShuffelled(1:m)) = true;
end
现在,当您想要恢复数据时,只需执行
data(idx)
或更可能是 data(idx,:)
之类的东西,因为您的 data
可能不是向量。但在那种情况下,您需要将我代码中的 numel
更改为 size(data,1)
或类似的
我有一个标签向量labels
,其中包含 10 个 class 的 60000 个对象的标签信息(每个 class 有 6000 个样本)。
我需要随机抽取1000个样本,还要保证每个100个class。
我假设您的数据是随机排序的?所以像这样(为了简单起见,我将只使用 3 个 class、1
、2
和 3
):
data = [ones(n,1); ones(n,1)*2; ones(n,1)*3];
data = data(randperm(numel(data)));
所以现在你想要 m*3
个样本,每个 class 个样本有 m
个样本(其中 m <= n
)。最自然的方法是对每个 class 精确 m
个样本不那么严格,只选择 m*3
个样本 uniformly-randomly:
idx = randperm(numel(data));
sample = data(numel(data))
请注意,如果您有统计工具箱,则可以使用 randsample
而不是 randperm
。
但是,如果您必须准确地 m
每个样本,那么应该这样做。请注意,我的目标是获取索引而不是值,因为我认为这更符合您的要求:
classes = unique(data);
k = numel(classes);
idx = false(m*3,1);
for class = 1:k
%// find the element numbers for each element of that class
idxForClass = find(data == classes(class));
%// Shuffle them randomly
idxForClassShuffled = idxForClass(randperm(numel(idxForClass))); %// or numel(n)
%// Pick the first m from the shuffled list
idx(idxForClassShuffelled(1:m)) = true;
end
现在,当您想要恢复数据时,只需执行
data(idx)
或更可能是 data(idx,:)
之类的东西,因为您的 data
可能不是向量。但在那种情况下,您需要将我代码中的 numel
更改为 size(data,1)
或类似的