将numpy向量分解为整数向量和权重

时间:2018-02-21 19:25:12

标签: python numpy vector

我有一个numpy向量,并希望将其分成整数向量和权重列表,以便将向量乘以权重并将它们相加在一起得到原始向量。

例如:

vector = np.array([1.5, 5.5])

# decompose returns a list of tuples of (integer vector, weight)
decompose(vector) == [
 (array([1, 5]), 0.25),
 (array([1, 6]), 0.25),
 (array([2, 5]), 0.25),
 (array([2, 6]), 0.25)
]

new_vec = np.zeros((2,))
for vec, weight in decompose(vector):
    new_vec += weight * vec

np.allclose(vector, new_vec)  # Should be true

这就是我目前所拥有的:

def decompose(vector):
    """Decompose a vector into the integer vectors that when multiplied by their
    factors and added together form the original vectors"""
    assert vector.shape == (2,)
    int_vector = vector.astype(np.int32)
    extra_0 = vector[0] - int_vector[0]
    extra_1 = vector[1] - int_vector[1]

    ret = []
    bounds = [
        [(int_vector[0], 1 - extra_0)],
        [(int_vector[1], 1 - extra_1)]
    ]

    if extra_0:
        bounds[0].append((int_vector[0] + 1, extra_0))
    if extra_1:
        bounds[1].append((int_vector[1] + 1, extra_1))

    for component_0, weight_0 in bounds[0]:
        for component_1, weight_1 in bounds[1]:
            ret.append((np.array([component_0, component_1]), weight_0 * weight_1))
    return ret

它工作正常,但我想知道是否有更有效的方法。

0 个答案:

没有答案