在 python numpy 中解决以下问题的最佳和最有效的方法是什么:
给定一个权重向量:
weights = numpy.array([1, 5, 2])
和一个值(value)向量:
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)) ])
有没有更好的办法?
最佳答案
此操作称为 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]])
关于python - numpy - 列向量乘以行向量的标量乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15971257/