溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

關(guān)于keras.utils.to_categorical的使用方法

發(fā)布時(shí)間:2020-07-02 14:43:33 來源:億速云 閱讀:338 作者:清晨 欄目:開發(fā)技術(shù)

不懂關(guān)于keras.utils.to_categorical的使用方法?其實(shí)想解決這個(gè)問題也不難,下面讓小編帶著大家一起學(xué)習(xí)怎么去解決,希望大家閱讀完這篇文章后大所收獲。

如下所示:

to_categorical(y, num_classes=None, dtype='float32')

將整型標(biāo)簽轉(zhuǎn)為onehot。y為int數(shù)組,num_classes為標(biāo)簽類別總數(shù),大于max(y)(標(biāo)簽從0開始的)。

返回:如果num_classes=None,返回len(y) * [max(y)+1](維度,m*n表示m行n列矩陣,下同),否則為len(y) * num_classes。說出來顯得復(fù)雜,請看下面實(shí)例。

import keras

ohl=keras.utils.to_categorical([1,3])
# ohl=keras.utils.to_categorical([[1],[3]])
print(ohl)
"""
[[0. 1. 0. 0.]
 [0. 0. 0. 1.]]
"""
ohl=keras.utils.to_categorical([1,3],num_classes=5)
print(ohl)
"""
[[0. 1. 0. 0. 0.]
 [0. 0. 0. 1. 0.]]
"""

該部分keras源碼如下:

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.
  """
  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 = y.ravel()
  if not num_classes:
    num_classes = np.max(y) + 1
  n = y.shape[0]
  categorical = np.zeros((n, num_classes), dtype=dtype)
  categorical[np.arange(n), y] = 1
  output_shape = input_shape + (num_classes,)
  categorical = np.reshape(categorical, output_shape)
  return categorical

補(bǔ)充知識:keras筆記——keras.utils.to_categoracal()函數(shù)

keras.utils.to_categoracal (y, num_classes=None, dtype='float32')

將整形標(biāo)簽轉(zhuǎn)為onehot,y為int數(shù)組,num_classes為標(biāo)簽類別總數(shù),大于max (y),(標(biāo)簽從0開始的)。

返回:

如果num_classes=None, 返回 len(y)*[max(y)+1] (維度,m*n表示m行n列矩陣),否則為len(y)*num_classes。

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享關(guān)于keras.utils.to_categorical的使用方法內(nèi)容對大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,遇到問題就找億速云,詳細(xì)的解決方法等著你來學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI