Matlab/Octave 1-of-K representation

前端 未结 5 1780
北恋
北恋 2021-01-05 14:58

I have a y of size 5000,1 (matrix), which contains integers between 1 and 10. I want to expand those indices into a 1-of-10 vector. I.e., y contains 1,2,3... and I want it t

相关标签:
5条回答
  • 2021-01-05 15:26

    Consider the following:

    y = randi([1 10],[5 1]);       %# vector of 5 numbers in the range [1,10]
    yy = bsxfun(@eq, y, 1:10)';    %# 1-of-10 encoding
    

    Example:

    >> y'
    ans =
         8     8     4     7     2
    >> yy
    yy =
         0     0     0     0     0
         0     0     0     0     1
         0     0     0     0     0
         0     0     1     0     0
         0     0     0     0     0
         0     0     0     0     0
         0     0     0     1     0
         1     1     0     0     0
         0     0     0     0     0
         0     0     0     0     0
    
    0 讨论(0)
  • 2021-01-05 15:39

    I think you mean:

    y = [2 5 7];
    Y = zeros(5000,10);
    Y(:,y) = 1;
    

    After the question edit, it should be this instead:

    y = [2,5,7,9,1,4,5,7,8,9....]; //(size (1,5000))
    for i = 1:5000
        Y(i,y(i)) = 1;
    end
    
    0 讨论(0)
  • 2021-01-05 15:43

    You can try cellfun operations:

    function vector = onehot(vector,decimal)
        vector(decimal)=1;
    end
    aa=zeros(10,2);
    dec=[5,6];
    %split into columns
    C=num2cell(aa,1);
    D=num2cell(dec,1);
    onehotmat=cellfun("onehot",C,D,"UniformOutput",false);
    output=cell2mat(onehotmat);
    
    0 讨论(0)
  • 2021-01-05 15:50

    While sparse may be faster and save memory, an answer involving eye() would be more elegant as it is faster than a loop and it was introduced during the octave lecture of that class

    Here is an example for 1 to 4

    V = [3;2;1;4];
    I = eye(4);
    Vk = I(V, :);
    
    0 讨论(0)
  • 2021-01-05 15:51
    n=5
    Y = ceil(10*rand(n,1))
    Yexp = zeros(n,10);
    Yexp(sub2ind(size(Yexp),1:n,Y')) = 1
    

    Also, consider using sparse, as in: Creating Indicator Matrix.

    0 讨论(0)
提交回复
热议问题