【问题标题】:np_utils.to_categorical Reversenp_utils.to_categorical 反向
【发布时间】:2016-12-15 04:00:03
【问题描述】:
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.]]

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

【问题讨论】:

  • 您想要获得ids 还是arr?如果arr,我想我们也需要uniques
  • 我在找arr
  • 那么,我们是否也将uniques 作为decode() 的输入?
  • 我可以这样做,在编码处返回两个元素

标签: python numpy keras


【解决方案1】:

您可以使用np.argmax 检索那些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])

【讨论】:

  • wt 如果我的数组是类似 [a,b,c,d,e] 的 str
  • @hks014 a, b, .. 是字符串还是数字还是别的什么?
  • 类似[cat,dog,bird,fish]的东西,编码后会是[[0,0,1],[0,1,0],[0,1,1] ,[1,0,0]]
  • @hks014 np.argmax。因此,或者,您可以使用uniques[np.argmax(y_code,1)]np.take(uniques,np.argmax(y_code,1))
  • @hks014 它说什么?
猜你喜欢
  • 2017-08-18
  • 2014-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-29
  • 2015-04-21
  • 2013-05-06
  • 2018-01-29
相关资源
最近更新 更多