Matlab:将数据块随机分为相等大小的集合 [英] Matlab: Dividing chunks of data randomly into equal sized sets

查看:176
本文介绍了Matlab:将数据块随机分为相等大小的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大型数据集,需要将其随机分为5个几乎相等大小的集合以进行交叉验证.我以前很乐意使用_crossvalind_来划分集合,但是这次我需要一次将数据块划分为这些组.

I have a large dataset that I need to divide randomly into 5 almost equal sized sets for cross validation. I have happily used _crossvalind_ to divide into sets before, however this time I need to divide chunks of data into these groups at a time.

假设我的数据如下:

data = [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18];

然后我想将它们随机分为5组,每组2个,例如像这样

Then I want to divide them randomly into 5 groups in chunks of 2, e.g. like this

g1 = [3 4], [11 12]  
g2 = [9 10]  
g3 = [1 2], [15 16]  
g4 = [7 8], [17 18]  
g5 = [5 6], [13 14]

我想我可以使用一些for循环来做到这一点,但是我猜想在matlab中必须有一种更具成本效益的方法来做到这一点:-)

I think I can do this with some for-loops, but I'm guessing there must be a much more cost-efficient way to do it in matlab :-)

有什么建议吗?

推荐答案

我将您的需求解释为集合的随机排序,但是在每个集合中,元素的排序与父集合保持不变.您可以使用randperm随机排序集合的数量,并为元素使用线性索引.

I'm interpreting your needs to be random ordering of sets, but within each set, the ordering of elements is unchanged from the parent set. You can use randperm to randomly order the number of sets and use linear indexing for the elements.

dataElements=numel(data);%# get number of elements
totalGroups=5;
groupSize=dataElements/totalGroups;%# I'm assuming here that it's neatly divisible as in your example
randOrder=randperm(totalGroups);%# randomly order of numbers from 1 till totalGroups
g=reshape(data,groupSize,totalGroups)';             %'# SO formatting
g=g(randOrder,:);

g的不同行为您提供不同的分组.

The different rows of g give you the different groupings.

这篇关于Matlab:将数据块随机分为相等大小的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆