多分類標籤label 轉換為 one-hot形式的二進位制標籤:
阿新 • • 發佈:2018-11-05
方法1: a = ['A','B','A','C'] from sklearn.preprocessing import OneHotEncoder,LabelEncoder label_value = label_encoder.fit_transform(a) >>label_encoder.classes_ array(['A', 'B', 'C'], dtype='<U1') >>label_value array([0, 1, 0, 2], dtype=int64) encoder = OneHotEncoder() >>one_hot.toarray() [[ 1. 0. 0.] [ 0. 1. 0.] [ 1. 0. 0.] [ 0. 0. 1.]] 方法2: from sklearn.preprocessing import LabelBinarizer encoder = LabelBinarizer() one_hot = encoder.fit_transform(a) >>one_hot array([[1, 0, 0], [0, 1, 0], [1, 0, 0], [0, 0, 1]]) 方法3: 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