NumPy相当于Keras函数utils.to_categorical

Dan*_*nny 3 python numpy machine-learning keras

我有一个使用Keras进行机器学习的Python脚本。我正在建立X和Y分别是功能和标签。

标签的构建如下:

def main=():

   depth = 10
   nclass = 101
   skip = True
   output = "True"
   videos = 'sensor'
   img_rows, img_cols, frames = 8, 8, depth
   channel = 1 
   fname_npz = 'dataset_{}_{}_{}.npz'.format(
    nclass, depth, skip)

   vid3d = videoto3d.Videoto3D(img_rows, img_cols, frames)
   nb_classes = nclass

   x, y = loaddata(videos, vid3d, nclass,
                    output, skip)

   X = x.reshape((x.shape[0], img_rows, img_cols, frames, channel))
   Y = np_utils.to_categorical(y, nb_classes) # This needs to be changed
Run Code Online (Sandbox Code Playgroud)

Keras中使用的函数“ to_categorical”的解释如下:

to_categorical

keras.utils.to_categorical(y,num_classes = None)

将类向量(整数)转换为二进制类矩阵。

现在我正在使用NumPy。您能否让我知道如何构建相同的代码行才能工作?换句话说,我正在NumPy中寻找“ to_categorical”功能的等效项。

rvi*_*nas 7

这是一种简单的方法:

np.eye(nb_classes)[y]
Run Code Online (Sandbox Code Playgroud)


Pau*_*zer 0

像这样的东西(我不认为有内置的):

>>> import numpy as np
>>> 
>>> n_cls, n_smp = 3, 10
>>> 
>>> y = np.random.randint(0, n_cls, (n_smp,))
>>> y
array([0, 1, 1, 1, 2, 2, 1, 2, 1, 1])
>>> 
>>> res = np.zeros((y.size, n_cls), dtype=int)
>>> res[np.arange(y.size), y] = 1
>>> res
array([[1, 0, 0],
       [0, 1, 0],
       [0, 1, 0],
       [0, 1, 0],
       [0, 0, 1],
       [0, 0, 1],
       [0, 1, 0],
       [0, 0, 1],
       [0, 1, 0],
       [0, 1, 0]])
Run Code Online (Sandbox Code Playgroud)