[Numpy-discussion] Matrix dot product over an axis(for a 3d array/list of matrices)

Keith Goodman kwgoodman at gmail.com
Thu Jul 15 12:54:04 EDT 2010


On Thu, Jul 15, 2010 at 9:45 AM, Keith Goodman <kwgoodman at gmail.com> wrote:
> On Thu, Jul 15, 2010 at 9:38 AM, Emmanuel Bengio <bengioe at gmail.com> wrote:
>>
>> Hello,
>>
>> I have a list of 4x4 transformation matrices, that I want to "dot with" another list of the same size (elementwise).
>> Making a for loop that calculates the dot product of each is extremely slow,
>> I thought that maybe it's due to the fact that I have thousands of matrices and it's a python for loop and there's a high Python overhead.
>>
>> I do something like this:
>> >> for a,b in izip(Rot,Trans):
>> >>     c.append(numpy.dot(a,b))
>>
>> Is there a way to do this in one instruction?
>> Or is there a way to do this all using weave.inline?
>
> How about using list comprehension? And setting dot = numpy.dot. Would
> initializing the the c list first help?

Doesn't buy much:

>> def forloop(a, b):
   .....:     c = []
   .....:     for x, y in izip(a, b):
   .....:         c.append(np.dot(x, y))
   .....:     return c
   .....:
>> a = [np.random.rand(4,4) for i in range(10000)]
>> b = [np.random.rand(4,4) for i in range(10000)]
>>
>> timeit forloop(a, b)
10 loops, best of 3: 21.2 ms per loop
>>
>> dot = np.dot
>> timeit [dot(x, y) for x, y in izip(a, b)]
100 loops, best of 3: 19.2 ms per loop



More information about the NumPy-Discussion mailing list