我有一个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”函数的等价物。
答案 0 :(得分:4)
这是一个简单的方法:
np.eye(nb_classes)[y]
答案 1 :(得分: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]])
答案 2 :(得分: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