简体   繁体   English

在MATLAB中随机选择具有权重的矩阵行

[英]Randomly select rows of a matrix with weights in MATLAB

Say I want to randomly select 3 rows from matrix m 假设我要从矩阵m随机选择3行

m = [1 2 1; 1 1 1; 1 1 1; 2 1 1; 2 2 1; 1 1 1; 1 1 1; 2 1 1];
sample = m(randsample(1:length(m),3),:)

However, I want to randomly select rows with weights. 但是,我想随机选择具有权重的行。 So I need a vector that corresponds to each row of m . 所以我需要一个与m每一行相对应的向量。 I want to apply a weighting to each row depending on the number (or ratio) of 1 and 2 that are present in each row. 我想根据每行中存在的12的数量(或比率)对每行应用权重。

Perhaps something like this? 也许像这样?

w1 = 0.6;                 %weight of 1
w2 = 0.4;                 %weight of 2
w = m;
w(w == 1) = w1;
w(w == 2) = w2;
w = (sum(w,2))*0.1        %vector of weights

But this is wrong: 但这是错误的:

sample = m(randsample(1:length(m),2),:,true,w)

Please help. 请帮忙。

Staying with your code, I think you were needed to normalize the weights and then select rows based on the random samples calculated from randsample using the normalized weights. 与您的代码保持一致,我认为您需要对权重进行归一化,然后根据使用归一化权重从randsample计算出的随机样本来选择行。 So, the following changes are needed for your code - 因此,您的代码需要进行以下更改-

w = sum(w,2)./sum(sum(w,2)) %// Normalize weights
sample = m(randsample([1:size(m,1)], 3, true, w) ,:)

Or if I can start-over and want to make the code concise, I could do like so - 或者,如果我可以重新开始并希望使代码简洁,我可以这样做-

%// Inputs
m = [1 2 1; 1 1 1; 1 1 1; 2 1 1; 2 2 1; 1 1 1; 1 1 1; 2 1 1]
w1 = 0.6;                 %// weight of 1
w2 = 0.4;                 %// weight of 2

%// Scale each row of w according to the weights assigned for 1 and 2.
%// Thus, we will have weights for each row
sum_12wts = sum(w1.*(m==1),2) + sum(w2.*(m==2),2)

%// Normalize the weights, so that they add upto 1, as needed for use with
%// randsample
norm_weights = sum_12wts./sum(sum_12wts)

%// Get 3 random row indices from m using randsample based on normalized weights
row_ind = randsample([1:size(m,1)], 3, true, norm_weights) 

%// Index into m to get the desired output
out = m(row_ind,:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM