Created
October 11, 2013 18:31
-
-
Save zygmuntz/6939718 to your computer and use it in GitHub Desktop.
One way of doing one-hot encoding in Matlab
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% y is a vector of labels | |
y_one_hot = zeros( size( y, 1 ), n_classes ); | |
% assuming class labels start from one | |
for i = 1:n_classes | |
rows = y == i; | |
y_one_hot( rows, i ) = 1; | |
end |
Allowing all values in y (above doesn't work if any y is zero or negative):
[~, loc] = ismember(y, unique(y));
y_one_hot = ind2vec(loc')';
This is nice as it also works for cell strings:
ystr = cellstr(char('hey', 'hey', 'gurl', 'hey'));
[~, loc] = ismember(ystr, unique(ystr));
y_one_hot = ind2vec(loc')';
array2table(full(y_one_hot), 'VariableNames', unique(ystr))
y_one_hot = ind2vec(y')'; // matlab has this built-in function
y_one_hot = full(ind2vec(y',num_classes)) is a clean way to do this.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
y_one_hot = ind2vec(y')'; // matlab has this built-in function