Gan*_*dar 5 python arrays hash numpy vectorization
我想知道是否有人知道如何在Python中矢量化特征哈希.例如,这是我的代码:
import numpy as np
hashlen = 5
x = np.array([4, 7, 4, 2, 6, 8, 0, 6, 3, 1])
h = np.array([0, 3, 1, 2, 4, 2, 1, 0, 3, 1])
Run Code Online (Sandbox Code Playgroud)
在特征散列中,h表示我正在散列x到的新向量的索引,即散列向量的索引0应该有4和6求和,索引1应该有4,0和1求和,等等.散列矢量应该是:
w = np.array([ 10, 5, 10, 10, 6])
Run Code Online (Sandbox Code Playgroud)
这样做的一种方法当然是循环遍历哈希索引,即:
for itr in range(hashlen):
w[itr] = np.sum(x[np.where(h==itr)])
Run Code Online (Sandbox Code Playgroud)
对于大向量,复杂度是hashlen(散列向量的长度)的函数.它可能需要很长时间,特别是在其中有一个np.where().
我想做的事情如下:
w = np.zeros(hashlen)
w[h]+= x
Run Code Online (Sandbox Code Playgroud)
但是,结果与此相同
w = np.zeros(hashlen)
w[h] = x
Run Code Online (Sandbox Code Playgroud)
如果我在这里遗失了什么,谁能告诉我?或者,如果有一种"简单"的方法来进行不涉及太多计算的特征散列?
您可以使用带权重的bincount来执行您要求的操作:
>>> np.bincount(h,weights=x)
array([ 10., 5., 10., 10., 6.])
Run Code Online (Sandbox Code Playgroud)
对于矩阵:
>>> import numpy as np
>>> a=np.random.randint(0,5,(50,50))
>>> rand=np.random.rand(5)
>>> rand
array([ 0.10899745, 0.35296303, 0.21127571, 0.56433924, 0.27895281])
>>> b=np.take(rand,a)
#Unfortunately you cannot do it like this:
>>> np.bincount(a,weights=b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: object too deep for desired array
#There we go:
>>> np.bincount(a.flat,weights=b.flat)
array([ 55.04371257, 172.59892108, 96.34172236, 297.40677707,
145.89232039])
Run Code Online (Sandbox Code Playgroud)
这使用了花哨的索引来查看发生了什么:
>>> np.bincount(a.flat)
array([505, 489, 456, 527, 523])
>>> np.bincount(a.flat)*rand
array([ 55.04371257, 172.59892108, 96.34172236, 297.40677707,
145.89232039])
Run Code Online (Sandbox Code Playgroud)