Matlab/Octave 1-of-K representation

丶灬走出姿态 提交于 2019-11-30 20:34:28
cyborg
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.

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

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

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

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