# to_categorical & one hot encoding ###### tags: `python語法` to_categorical就是將類別向量轉換為二進制(只有0和1)的矩陣類型表示。其表現為將原有的類別向量轉換為one hot encoding的形式 ```python= from keras.utils.np_utils import * #類別向量定義 b = [0,1,2,3,4,5,6,7,8] #使用to_categorical將b按照9個類别来進行轉換 b = to_categorical(b, 9) print(b) 執行结果如下: [[1. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 1. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 1. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 1. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 1. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 1. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 1. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 1. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 1.]] ``` one hot encoding ```python= def convert_to_one_hot(labels, num_classes): #計算向量有多少行 num_labels = len(labels) #生成值全為0的矩陣 labels_one_hot = np.zeros((num_labels, num_classes)) #計算向量中每個類别值在最终生成的矩陣的位置 index_offset = np.arange(num_labels) * num_classes #為每個類别的位置標記上1 labels_one_hot.flat[index_offset + labels] = 1 return labels_one_hot #進行測試 b = [2, 4, 6, 8, 6, 2, 3, 7] print(convert_to_one_hot(b,9)) 測試结果: [[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. 1. 0. 0.] [0. 0. 1. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 1. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 1. 0.]] ```