tf.keras.utils.to_categorical(one hot编码)

语法

tf.keras.utils.to_categorical(y,num_classes,dtype)
参数
  • y:要转换的值
  • num_classes:类别数量
  • dtype:数据类型,默认float32
返回值
  • numpy类型,one hot编码

例子

一维

import tensorflow as tf
import numpy as np

arr=np.array([0,1,2,3])

train_label_onehot=tf.keras.utils.to_categorical(arr)

print(train_label_onehot.shape)
print(train_label_onehot)

执行结果:

(4, 4)
[[1. 0. 0. 0.]
 [0. 1. 0. 0.]
 [0. 0. 1. 0.]
 [0. 0. 0. 1.]]

二维

arr=np.array([[0,1,2,3],[3,2,1,0]])
train_label_onehot=tf.keras.utils.to_categorical(arr)
train_label_onehot

执行结果:

array([[[1., 0., 0., 0.],
        [0., 1., 0., 0.],
        [0., 0., 1., 0.],
        [0., 0., 0., 1.]],

       [[0., 0., 0., 1.],
        [0., 0., 1., 0.],
        [0., 1., 0., 0.],
        [1., 0., 0., 0.]]], dtype=float32)

对独热编码 解码

print(np.argmax(train_label_onehot,axis=1))