在python numpy中解决以下问题的最佳和最有效的方法是什么:
给出权重向量:
weights = numpy.array([1, 5, 2])
和值向量:
values = numpy.array([1, 3, 10, 4, 2])
结果我需要一个矩阵,其中每行包含values
向量标量乘以weights[row]
的值:
result = [
[1, 3, 10, 4, 2],
[5, 15, 50, 20, 10],
[2, 6, 20, 8, 4]
]
我找到的一个解决方案如下:
result = numpy.array([ weights[n]*values for n in range(len(weights)) ])
有更好的方法吗?
答案 0 :(得分:8)
此操作称为outer product。可以使用numpy.outer()
:
In [6]: numpy.outer(weights, values)
Out[6]:
array([[ 1, 3, 10, 4, 2],
[ 5, 15, 50, 20, 10],
[ 2, 6, 20, 8, 4]])
答案 1 :(得分:3)
您可以将weights
重塑为维度(3,1)数组,然后将其乘以values
weights = numpy.array([1, 5, 2])[:,None] #column vector
values = numpy.array([1, 3, 10, 4, 2])
result = weights*values
print(result)
array([[ 1, 3, 10, 4, 2],
[ 5, 15, 50, 20, 10],
[ 2, 6, 20, 8, 4]])
This answer解释了[:,None]