【发布时间】: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_values、col是什么? -
col - 我要更改的列的索引,即删除并通过附加转换为one-hot。 unique_values -- 字典。类似于 ['categorical_value_2'] = 2。所以这个字典的长度是 one_hot 的最大值的数量。
标签: numpy tensorflow one-hot-encoding