首页 > 其他分享 >学习笔记426—keras中to_categorical函数解析

学习笔记426—keras中to_categorical函数解析

时间:2023-10-10 12:55:18浏览次数:32  
标签:num keras labels categorical shape classes np 426

keras中to_categorical函数解析

1.to_categorical的功能

简单来说,to_categorical就是将类别向量转换为二进制(只有0和1)的矩阵类型表示。其表现为将原有的类别向量转换为独热编码的形式。先上代码看一下效果:

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.]]

to_categorical最为keras中提供的一个工具方法,从以上代码运行可以看出,将原来类别向量中的每个值都转换为矩阵里的一个行向量,从左到右依次是0,1,2,...8个类别。2表示为[0. 0. 1. 0. 0. 0. 0. 0. 0.],只有第3个为1,作为有效位,其余全部为0。
2.one_hot encoding(独热编码)介绍

独热编码又称为一位有效位编码,上边代码例子中其实就是将类别向量转换为独热编码的类别矩阵。也就是如下转换:

     0  1  2  3  4  5  6  7  8
0=> [1. 0. 0. 0. 0. 0. 0. 0. 0.]
1=> [0. 1. 0. 0. 0. 0. 0. 0. 0.]
2=> [0. 0. 1. 0. 0. 0. 0. 0. 0.]
3=> [0. 0. 0. 1. 0. 0. 0. 0. 0.]
4=> [0. 0. 0. 0. 1. 0. 0. 0. 0.]
5=> [0. 0. 0. 0. 0. 1. 0. 0. 0.]
6=> [0. 0. 0. 0. 0. 0. 1. 0. 0.]
7=> [0. 0. 0. 0. 0. 0. 0. 1. 0.]
8=> [0. 0. 0. 0. 0. 0. 0. 0. 1.]

 那么一道思考题来了,让你自己编码实现类别向量向独热编码的转换,该怎样实现呢?

以下是我自己粗浅写的一个小例子,仅供参考:

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.]]

 3.源码解析

to_categorical在keras的utils/np_utils.py中,源码如下:

def to_categorical(y, num_classes=None, dtype='float32'):
    """Converts a class vector (integers) to binary class matrix.
    E.g. for use with categorical_crossentropy.
    # Arguments
        y: class vector to be converted into a matrix
            (integers from 0 to num_classes).
        num_classes: total number of classes.
        dtype: The data type expected by the input, as a string
            (`float32`, `float64`, `int32`...)
    # Returns
        A binary matrix representation of the input. The classes axis
        is placed last.
    # Example
    ```python
    # Consider an array of 5 labels out of a set of 3 classes {0, 1, 2}:
    > labels
    array([0, 2, 1, 2, 0])
    # `to_categorical` converts this into a matrix with as many
    # columns as there are classes. The number of rows
    # stays the same.
    > to_categorical(labels)
    array([[ 1.,  0.,  0.],
           [ 0.,  0.,  1.],
           [ 0.,  1.,  0.],
           [ 0.,  0.,  1.],
           [ 1.,  0.,  0.]], dtype=float32)
    ```
    """
    #将输入y向量转换为数组
    y = np.array(y, dtype='int')
    #获取数组的行列大小
    input_shape = y.shape
    if input_shape and input_shape[-1] == 1 and len(input_shape) > 1:
        input_shape = tuple(input_shape[:-1])
    #y变为1维数组
    y = y.ravel()
    #如果用户没有输入分类个数,则自行计算分类个数
    if not num_classes:
        num_classes = np.max(y) + 1
    n = y.shape[0]
    #生成全为0的n行num_classes列的值全为0的矩阵
    categorical = np.zeros((n, num_classes), dtype=dtype)
    #np.arange(n)得到每个行的位置值,y里边则是每个列的位置值
    categorical[np.arange(n), y] = 1
    #进行reshape矫正
    output_shape = input_shape + (num_classes,)
    categorical = np.reshape(categorical, output_shape)
    return categorical

参考链接:https://blog.csdn.net/moyu123456789/article/details/83444140

 

标签:num,keras,labels,categorical,shape,classes,np,426
From: https://www.cnblogs.com/hechangchun/p/17754400.html

相关文章

  • Keras Model 和 Sequential
    KerasModelhttps://cloud.tencent.com/developer/article/2162930===============================================================Keras模型Keras提供的模型,其中分为两类:Sequential顺序模型Model类模型我们可以通过fromkeras.modelsimportSequential或者fro......
  • Keras MaxPooling2D
     KerasMaxPooling2D 2D最大池化层   keras.layers.MaxPooling2D(pool_size=(2,2),                             strides=None,                             padding='valid',           ......
  • Keras Flatten
    KerasFlatten===============================================================作用:Flatten层用来将输入“压平”,即把多维的输入一维化,常用在从卷积层到全连接层的过渡。Flatten不影响batch的大小。例子:   fromkeras.modelsimportSequential   fromkeras.layers.c......
  • Keras Dropout
    =============================================================== 一、Keras中使用Dropout正则化减少过度拟合Dropout正则化是最简单的神经网络正则化方法。其原理非常简单粗暴:任意丢弃神经网络层中的输入,该层可以是数据样本中的输入变量或来自先前层的激活。它能够模拟具......
  • keras.layers. K.function 用法(keras提取中间层的输出)
    https://www.laike.net/article-11-295083-0.html 使用K.function()调试keras操作Keras的底层库使用Theano或TensorFlow,这两个库也称为Keras的后端。无论是Theano还是TensorFlow,都需要提前定义好网络的结构,也就是常说的“计算图”。在运行前需要对计算图编译,然后才能输出结果......
  • 解决tansorflow新手教程的keras.datasets数据下载问题
    portal>https://github.com/tensorflow/tensorflow/issues/33285......
  • 2023-2024-1 20231426 《计算机基础与程序设计》第一周学习总结
    作业信息这个作业属于哪个课程2022-2023-1-计算机基础与程序设计这个作业要求在哪里2022-2023-1计算机基础与程序设计第一周作业这个作业的目标初步熟悉课本以及对所学内容有所思考作业正文本博客教材学习内容总结本书涉及计算机科学的方方面面,介绍了计......
  • 学期:2023-2024-1 学号:20231426 《计算机基础与程序设计》第一周学习总结
    作业信息这个作业属于哪个课程2022-2023-1-计算机基础与程序设计这个作业要求在哪里2022-2023-1计算机基础与程序设计第一周作业这个作业的目标初步熟悉课本以及对所学内容有所思考作业正文教材学习内容总结大体认识了《计算机科学概论》这本书,了解其中......
  • 无涯教程-TensorFlow - Keras
    Keras易于学习的高级Python库,可在TensorFlow框架上运行,它的重点是理解深度学习技术,如为神经网络创建层,以维护形状和数学细节的概念。框架的创建可以分为以下两种类型-顺序API功能API无涯教程将使用JupyterNotebook执行和显示输出,如下所示-步骤1  - 首先执行数据加载和......
  • P4426 [HNOI/AHOI2018] 毒瘤 题解
    P4426[HNOI/AHOI2018]毒瘤题解非常好虚树题目,融合了容斥的内容。简化题意给定一张\(n\)个点、\(m\)条边的图,求图的独立集个数。其中\(n\leq10^5\),\(n-1\leqm\leqn+10\)。独立集:对于图\(G(U,E)\)的一个点集\(S\),\(\forall(u,v)\inE\),不存在\(u\inS\)且......