Matlab onehot 到整数

Matlab onehot to integers

我想在 MATLAB 中将 onehot 数组转换为整数值数组。给定:

Y =  1     0     0
     0     1     0
     0     1     0

我想return:

new_y = 1
        2
        2

您可以只使用 find 和 return 这样的列索引

Y = [1 0 0; 0 1 0; 0 1 0];

[~, new_y] = find(Y);   % output: [1; 2; 2] is the col indices of your 1s

同样,如果您的输入是转置,您可以 return 行索引

[new_y, ~] = find(Y);   % output: [1; 2; 3] is the row indices of your 1s

MATLAB 的神经网络工具箱具有用于在单热向量和索引之间进行转换的内置函数:ind2vec() to create a one-hot matrix, and vec2ind() 将单热矩阵转换回索引向量。

注:ind2vecreturns一个稀疏矩阵。要将其转换为完整矩阵,您必须使用 full() 函数。

>> Y = full(ind2vec([1, 2, 3]))

Y =    

     1     0     0
     0     1     0
     0     0     1

>> new_y = vec2ind(Y)

new_y =

     1     2     3