np_utils.to_范畴反转

2024-04-25 01:12:33 发布

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

import numpy as np
from keras.utils import np_utils
nsample = 100
sample_space = ["HOME","DRAW","AWAY"]
array = np.random.choice(sample_space, nsample, )
uniques, coded_id = np.unique(array, return_inverse=True)
coded_array = np_utils.to_categorical(coded_id)

示例

输入

 ['AWAY', 'HOME', 'DRAW', 'AWAY', ...]

输出编码阵列

[[ 0.  1.  0.]
 [ 0.  0.  1.]
 [ 0.  0.  1.]
 ..., 
 [ 0.  0.  1.]
 [ 0.  0.  1.]
 [ 1.  0.  0.]]

如何从编码数组中逆向处理并获取原始数据?


Tags: sampleimportnumpyid编码homeasnp
1条回答
网友
1楼 · 发布于 2024-04-25 01:12:33

您可以使用^{}检索那些ids,然后简单地索引到uniques中就可以得到原始数组。因此,我们会有一个实现,就像这样-

uniques[y_code.argmax(1)]

样本运行-

In [44]: arr
Out[44]: array([5, 7, 3, 2, 4, 3, 7])

In [45]: uniques, ids = np.unique(arr, return_inverse=True)

In [46]: y_code = np_utils.to_categorical(ids, len(uniques))

In [47]: uniques[y_code.argmax(1)]
Out[47]: array([5, 7, 3, 2, 4, 3, 7])

相关问题 更多 >