Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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[n] for n in range(len(weights)) ]

vector_answer = [0,0,0]
for x in wmatrix: vector_answer+=x
like image 878
Pete Avatar asked Feb 21 '11 17:02

Pete


1 Answers

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!

like image 111
eat Avatar answered Sep 27 '22 23:09

eat