keras中的keras.utils.to_categorical方法


參考鏈接:https://blog.csdn.net/nima1994/article/details/82468965 

參考鏈接:https://blog.csdn.net/gdl3463315/article/details/82659378

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。
 

  1.  
    import keras
  2.  
     
  3.  
    ohl=keras.utils.to_categorical([ 1,3])
  4.  
    # ohl=keras.utils.to_categorical([[1],[3]])
  5.  
    print(ohl)
  6.  
    """
  7.  
    [[0. 1. 0. 0.]
  8.  
    [0. 0. 0. 1.]]
  9.  
    """
  10.  
    ohl=keras.utils.to_categorical([ 1,3],num_classes=5)
  11.  
    print(ohl)
  12.  
    """
  13.  
    [[0. 1. 0. 0. 0.]
  14.  
    [0. 0. 0. 1. 0.]]
  15.  
    """

該部分keras源碼如下:

  1.  
    def to_categorical(y, num_classes=None, dtype='float32'):
  2.  
    """Converts a class vector (integers) to binary class matrix.
  3.  
     
  4.  
    E.g. for use with categorical_crossentropy.
  5.  
     
  6.  
    # Arguments
  7.  
    y: class vector to be converted into a matrix
  8.  
    (integers from 0 to num_classes).
  9.  
    num_classes: total number of classes.
  10.  
    dtype: The data type expected by the input, as a string
  11.  
    (`float32`, `float64`, `int32`...)
  12.  
     
  13.  
    # Returns
  14.  
    A binary matrix representation of the input. The classes axis
  15.  
    is placed last.
  16.  
    """
  17.  
    y = np.array(y, dtype= 'int')
  18.  
    input_shape = y.shape
  19.  
    if input_shape and input_shape[-1] == 1 and len(input_shape) > 1:
  20.  
    input_shape = tuple(input_shape[: -1])
  21.  
    y = y.ravel()
  22.  
    if not num_classes:
  23.  
    num_classes = np.max(y) + 1
  24.  
    n = y.shape[ 0]
  25.  
    categorical = np.zeros((n, num_classes), dtype=dtype)
  26.  
    categorical[np.arange(n), y] = 1
  27.  
    output_shape = input_shape + (num_classes,)
  28.  
    categorical = np.reshape(categorical, output_shape)
  29.  
    return categorical
  30.  
     

簡單來說:**keras.utils.to_categorical函數:是把類別標簽轉換為onehot編碼(categorical就是類別標簽的意思,表示現實世界中你分類的各類別), 而onehot編碼是一種方便計算機處理的二元編碼。**


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM