【问题标题】:one-hot encoding and existing dataone-hot 编码和现有数据
【发布时间】:2018-03-24 09:49:50
【问题描述】:

我有一个 numpy 数组 (N,M),其中一些列应该是一次性编码的。请帮助使用 numpy 和/或 tensorflow 进行 one-hot 编码。

例子:

[
[ 0.993, 0, 0.88 ]
[ 0.234, 1, 1.00 ]
[ 0.235, 2, 1.01 ]
.....
]

这里的第二列(值为 3 和 2 )应该是一个热编码,我知道只有 3 个不同的值( 0, 1, 2 )。

生成的数组应如下所示:

[
[ 0.993, 0.88, 0, 0, 0 ]
[ 0.234, 1.00, 0, 1, 0 ]
[ 0.235, 1.01, 1, 0, 0 ]
.....
]

这样我就可以将这个数组输入到张量流中。 请注意,第二列已被删除,并且它的 one-hot 版本被附加到每个子数组的末尾。

任何帮助将不胜感激。 提前致谢。

更新

这是我现在拥有的: 嗯,不完全是…… 1.我在数组中有超过 3 列......但我仍然想只用第 2 列.. 2.第一个数组是结构化的,即它的形状是(N,)

这是我所拥有的:

def one_hot(value, max_value):
    value = int(value)
    a = np.zeros(max_value, 'uint8')
    if value != 0:
        a[value] = 1
    return a

# data is structured array with the shape of (N,)
# it has strings, ints, floats inside..
# was get by np.genfromtxt(dtype=None)

unique_values = dict()
unique_values['categorical1'] = 1
unique_values['categorical2'] = 2
for row in data:
   row[col] = unique_values[row[col]]

codes = np.zeros((data.shape[0], len(unique_values)))

idx = 0
for row in data:
   codes[idx] = one_hot(row[col], len(unique_values))  # could be optimised by not creating new array every time
   idx += 1

data = np.c_[data[:, [range(0, col), range(col + 1, 32)]], codes[data[:, col].astype(int)]]

还尝试通过以下方式连接:

print data.shape # shape (5000,)
print codes.shape # shape (5000,3)
data = np.concatenate((data, codes), axis=1)

【问题讨论】:

  • 第二列的值为 0,1,2。我看不到它是如何创建所述的单热编码附加数组的。可能是错字?
  • 0 编码为 0,0,0。1 编码为 0,1,0。2 编码为 1,0,0
  • 我不需要精确的二进制表示值。我的意思是如果 2 将被编码为 0、0、1 和 1 将被编码为 1、0、0 这对我来说也很好,但我认为 0 应该被编码为 0、0、0。
  • unique_valuescol 是什么?
  • col - 我要更改的列的索引,即删除并通过附加转换为one-hot。 unique_values -- 字典。类似于 ['categorical_value_2'] = 2。所以这个字典的长度是 one_hot 的最大值的数量。

标签: numpy tensorflow one-hot-encoding


【解决方案1】:

这是一种方法 -

In [384]: a # input array
Out[384]: 
array([[ 0.993,  0.   ,  0.88 ],
       [ 0.234,  1.   ,  1.   ],
       [ 0.235,  2.   ,  1.01 ]])

In [385]: codes = np.array([[0,0,0],[0,1,0],[1,0,0]]) # define codes here

In [387]: codes
Out[387]: 
array([[0, 0, 0],   # encoding for 0
       [0, 1, 0],   # encoding for 1
       [1, 0, 0]])  # encoding for 2

# Slice out the second column and append one-hot encoded array
In [386]: np.c_[a[:,[0,2]], codes[a[:,1].astype(int)]]
Out[386]: 
array([[ 0.993,  0.88 ,  0.   ,  0.   ,  0.   ],
       [ 0.234,  1.   ,  0.   ,  1.   ,  0.   ],
       [ 0.235,  1.01 ,  1.   ,  0.   ,  0.   ]])

【讨论】:

  • 假设我有一个数组: [ [ 0.993, 0, 0.88 ] [ 0.234, 1, 1.00 ] [ 0.235, 2, 1.01 ] [ 0.234, 0, 2.01 ] .....]您能否包括基于源数组的代码数组的动态生成?
  • @user3489820 无论如何都应该工作。将其用作新的 a 并且无需更改任何其他内容即可工作。
  • 好吧,我相信它帮助我走得更远,但我仍然是堆栈.. 第一个:我有结构化数组,即它的形状 (N,) 第二个:我有超过 3 列。 .. 请检查我的帖子,看看我现在在哪里。我会将问题标记为已回答,但如果您能帮助我更进一步,我将不胜感激。
猜你喜欢
  • 2017-11-06
  • 2018-03-29
  • 2019-06-28
  • 2020-12-13
  • 2021-11-02
  • 2017-02-16
  • 1970-01-01
  • 2017-06-21
  • 2021-04-14
相关资源
最近更新 更多