NumPy相当于Keras函数utils.to\u分类

2024-05-19 10:22:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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_category”解释如下:

to_categorical

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

Converts a class vector (integers) to binary class matrix.

现在我用的是NumPy。你能告诉我如何建立相同的代码行,以便工作?换言之,我正在寻找与NumPy中的“to-tu-category”功能相当的功能。在


Tags: totrueimgoutputframes标签videosclasses
3条回答

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

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

这里有一个简单的方法:

np.eye(nb_classes)[y]

尝试使用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

相关问题 更多 >

    热门问题