Skip to content

Instantly share code, notes, and snippets.

@davidnvq
Created April 24, 2018 01:27
Show Gist options
  • Save davidnvq/d6348df4315120d9aa77db76ec08434a to your computer and use it in GitHub Desktop.
Save davidnvq/d6348df4315120d9aa77db76ec08434a to your computer and use it in GitHub Desktop.
Convert multi-labels of an instance to one-hot encoding.
import numpy as np
n_classes = 10
class_matrix = np.eye(n_classes)
"""
class_matrix should be obtained as below:
array([[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],
[0, 0, 0, 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, 0, 0, 0, 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, 0, 0, 0, 1]])
"""
# for an instance with labels `y` = [0, 1, 3, 6]
# so, the new encoded labels must include the lines in
# class_matrix with index [0, 1, 3, 6]. It becomes easy now.
y_encoded = class_matrix[y, :]
# We are done here.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment