to_categorical实现独热编码
函数声明: to_categorical(y, num_classes=None, dtype=‘float32’)
作用:将整型标签转为onehot。y为int数组,num_classes为标签类别总数,大于max(y)(标签从0开始的)。
返回:如果num_classes=None,返回len(y) * [max(y)+1](维度,m*n表示m行n列矩阵,下同),否则为len(y) * num_classes。
import tensorflow as tf oh1=tf.keras.utils.to_categorical([1,3]) # oh1=keras.utils.to_categorical([[1],[3]]) print(oh1) """ [[0. 1. 0. 0.] [0. 0. 0. 1.]] """ oh2=tf.keras.utils.to_categorical([1,3],num_classes=5) print(oh2) """ [[0. 1. 0. 0. 0.] [0. 0. 0. 1. 0.]] """
num_classes默认为以数组里面最大的为编码依据,也可以指定编码依据,比如num_classes = 10。
简而言之,就是将给定的序列,编码成一个one -hot矩阵。注意编号是从0开始的。
因为tensorflow已经集成了keras,所以可以直接tf.keras使用该函数。
这种实现的独热编码是一个数组,下面通过tf.one_hot()实现的输出的是一个tensorflow的tensor
tf.one_hot()实现独热编码
import tensorflow as tf indices = [0,2,3,5] depth1 = 6 # indices没有元素超过(depth-1) depth2 = 4 # indices有元素超过(depth-1) a = tf.one_hot(indices,depth1) b = tf.one_hot(indices,depth2) print(a) print(b) ''' tf.Tensor( [[1. 0. 0. 0. 0. 0.] [0. 0. 1. 0. 0. 0.] [0. 0. 0. 1. 0. 0.] [0. 0. 0. 0. 0. 1.]], shape=(4, 6), dtype=float32) tf.Tensor( [[1. 0. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.] [0. 0. 0. 0.]], shape=(4, 4), dtype=float32) '''
####本博客是学习记录用的,参考了网上其他博客的资料,如有侵权请告知!
来源:51CTO
作者:weixin_40744639
链接:https://blog.csdn.net/weixin_40744639/article/details/100822739