体温计编码 [英] Numpy thermometer encoding
问题描述
我正在尝试使用numpy优化的内置函数来生成温度计编码.如果给定长度为1,温度计编码基本上会生成 n 数量.例如,在8长度中,3将被编码为:
I am trying to use numpy optimized in-built functions to generate thermometer encoding. Thermometer encoding is basically generating n amount if 1's in a given length. For example in 8-length, 3 will be encoded as:
1 1 1 0 0 0 0 0
使用numpy根据整数输入生成矢量基本上是切片并设置1.
Using numpy to generate that vector based on a integer input is basically slicing and setting 1.
stream[:num_ones] = 1
所以给我的问题一个 vector 作为输入,什么是生成矩阵输出的最佳方法,例如:
So my question is given a vector as input what will be best way to generate a matrix output for instance:
[2 3 4 1]
输入应产生:
[[1 1 0 0 0 0 0 0],
[1 1 1 0 0 0 0 0],
[1 1 1 1 0 0 0 0],
[1 0 0 0 0 0 0 0]]
我当前的解决方案是遍历所需大小的零矩阵,并使用我上面编写的切片方法将所需元素数设置为1.我有更快的方法吗?
My current solution is iterating over the a zero matrix of required size and setting the required number of elements to 1 using the slicing method I wrote above. Is there a faster way for me to do this?
推荐答案
我以前从未听说过温度计编码",但是当您意识到它与一次性编码如此相似时,很显然您可以到达那里使用移位操作:
I'd never heard of "thermometer encoding" before, but when you realise how it's so similar to one-hot encoding, it becomes clear you can get there using bit shift ops:
>>> a = np.array([2, 3, 4, 1], dtype=np.uint8)
>>> print(np.fliplr(np.unpackbits((1 << a) - 1).reshape(-1,8)))
[[1 1 0 0 0 0 0 0]
[1 1 1 0 0 0 0 0]
[1 1 1 1 0 0 0 0]
[1 0 0 0 0 0 0 0]]
您可以通过处理8个列块,将其概括为任意大小的整数:
You can generalise the idea to arbitrary size integers by working in 8 column chunks:
a = np.array([2, 13, 4, 0, 1, 17], dtype=np.uint8)
out = np.empty((len(a), 0), dtype=np.uint8)
while a.any():
block = np.fliplr(np.unpackbits((1 << a) - 1).reshape(-1,8))
out = np.concatenate([out, block], axis=1)
a = np.where(a<8, 0, a-8)
print(out)
[[1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0]
[1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0]]
这篇关于体温计编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!