开发者

Numpy- weight and sum rows of a matrix

Using Python & Numpy, I would like to:

  • Consider each row of an (n columns x m rows) matrix as a vector
  • Weight each row (scalar multiplication on each component of the vector)
  • Add each row to create a final vector (vector addition).

The weights are given in a regular numpy array, n x 1, so that each vector m in the matrix should be multiplied by weight n.

Here's what I've got (with test data; the actual matrix is huge), which is perhaps very un-Numpy and un-Pythonic. Can anyone do better? Thanks!

import numpy

# test data
mvec1 = numpy.array([1,2,3])
mvec2 = numpy.array([4,5,6])
start_matrix = numpy.matrix([mvec1,mvec2])
weights = numpy.array([0.5,-1])

#computation
wmatrix = [ weights[n]*start_matrix开发者_如何学C[n] for n in range(len(weights)) ]

vector_answer = [0,0,0]
for x in wmatrix: vector_answer+=x


Even a 'technically' correct answer has been all ready given, I'll give my straightforward answer:

from numpy import array, dot
dot(array([0.5, -1]), array([[1, 2, 3], [4, 5, 6]]))
# array([-3.5 -4. -4.5])

This one is much more on with the spirit of linear algebra (and as well those three dotted requirements on top of the question).

Update: And this solution is really fast, not marginally, but easily some (10- 15)x faster than all ready proposed one!


It will be more convenient to use a two-dimensional numpy.array than a numpy.matrix in this case.

start_matrix = numpy.array([[1,2,3],[4,5,6]])
weights = numpy.array([0.5,-1])
final_vector = (start_matrix.T * weights).sum(axis=1)
# array([-3.5, -4. , -4.5])

The multiplication operator * does the right thing here due to NumPy's broadcasting rules.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜