首页 文章

NumPy相当于Keras函数utils.to_categorical

提问于
浏览
1

我有一个Python脚本,它使用Keras进行机器学习 . 我正在构建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

Keras中使用的“to_categorical”功能解释如下:

to_categorical keras.utils.to_categorical(y,num_classes = None)将类向量(整数)转换为二进制类矩阵 .

现在我正在使用NumPy . 您可以告诉我如何构建相同的代码行以便工作吗?换句话说,我正在寻找NumPy中“to_categorical”函数的等价物 .

3 回答

  • 0

    尝试使用get_dummies .

    >>> pd.core.reshape.get_dummies(df)
    Out[30]: 
       cat_a  cat_b  cat_c
    0      1      0      0
    1      1      0      0
    2      1      0      0
    3      0      1      0
    4      0      1      0
    5      0      0      1
    
  • 0

    这是一种简单的方法:

    np.eye(nb_classes)[y]
    
  • 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]])
    

相关问题