【问题标题】:Vectorizing feature hashing in python在 python 中矢量化特征散列
【发布时间】:2013-08-01 06:57:18
【问题描述】:

我想知道是否有人知道如何在 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])

在特征散列中,h 表示我将 x 散列到的新向量的索引,即散列向量的索引 0 应该有 4 和 6 相加,索引 1 应该有 4、0 和 1 相加等. 得到的散列向量应该是:

    w = np.array([ 10, 5, 10, 10, 6])

这样做的一种方法当然是循环遍历哈希索引,即:

    for itr in range(hashlen):
        w[itr] = np.sum(x[np.where(h==itr)])

对于大向量,复杂度是 hashlen(散列向量的长度)的函数。这可能需要很长时间,尤其是其中包含 np.where()。

我想做这样的事情:

    w = np.zeros(hashlen)
    w[h]+= x

但是这样做的结果和做的一样

    w = np.zeros(hashlen)
    w[h] = x

如果我在这里遗漏了什么,谁能告诉我?或者是否有一种“简单”的方式来进行特征散列而不涉及太多计算?

【问题讨论】:

    标签: python arrays hash numpy vectorization


    【解决方案1】:

    您可以使用带有权重的 bincount 来完成您的要求:

    >>> np.bincount(h,weights=x)
    array([ 10.,   5.,  10.,  10.,   6.])
    

    对于矩阵:

    >>> 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])
    

    这使用了花哨的索引来查看发生了什么:

    >>> 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])
    

    【讨论】:

    • 正是我想要的。非常感谢!
    • 只是好奇 - 是否可以在矩阵而不是向量上做类似的事情?当然没有循环。
    • 更新了矩阵。如果您正在寻找其他东西,还有其他一些方法。
    • 不,我的意思是,当你散列它时,你不应该将它散列到向量;您应该将其散列为大小为 50x5 的矩阵(在这种情况下)。比如:z = np.zeros([50,5]) for itr in range(50): z[itr] = np.bincount(a[itr], weights=b[itr])
    • 我不确定这是否可能——查看一个执行类似操作的 numpy 函数 histogramdd,它实际上使用 np.digitize 循环遍历多维数组。最好用一个离散的例子把这个问题作为一个单独的问题来问。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 2019-06-13
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    相关资源
    最近更新 更多