Matlab/Octave 1-of-K representation

一世执手 提交于 2019-12-30 06:33:09

问题


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 to "expand" to:

1 0 0 0 0 0 0 0 0 0 
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 

What is the best way to do that?

I tried:

Y = zeros(5000,10); Y(y) = 1; 

but it didn't work.

It works for vectors though:

if y = [2 5 7], and Y = zeros(1,10), then Y(y) = [0 1 0 0 1 0 1 0 0 0].


回答1:


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.




回答2:


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



回答3:


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, :);



回答4:


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);



回答5:


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


来源:https://stackoverflow.com/questions/8054258/matlab-octave-1-of-k-representation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!