1. 程式人生 > >多分類標籤label 轉換為 one-hot的理解

多分類標籤label 轉換為 one-hot的理解

原始程式碼:

import numpy as np
def dense_to_one_hot(labels_dense, num_classes):
    """Convert class labels from scalars to one-hot vectors."""
    num_labels = labels_dense.shape[0]
    index_offset = np.arange(num_labels) * num_classes
    labels_one_hot = np.zeros((num_labels, num_classes))
    labels_one_hot.flat[index_offset+labels_dense.ravel()] = 1
    return labels_one_hot

測試:

設標籤

labels_dense = np.array([0,1,2,3,4]) ,則 num_classes = 5

labels_dense = np.array([0,1,2,3,4]) 
num_classes  = 5
dense_to_one_hot(labels_dense,num_classes)

將多標籤編碼為: