Suppose you have n square matrices A1,...,An. Is there anyway to multiply these matrices in a neat way? As far as I know dot in numpy accepts only two arguments. One obvious way is to define a function to call itself and get the result. Is there any better way to get it done?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
If you compute all the matrices a priori then you should use an optimization scheme for matrix chain multiplication. See this Wikipedia article.
Another way to achieve this would be using
einsum
, which implements the Einstein summation convention for NumPy.To very briefly explain this convention with respect to this problem: When you write down your multiple matrix product as one big sum of products, you get something like:
where
P
is the result of your product andA1
,A2
,A3
, andA4
are the input matrices. Note that you sum over exactly those indices that appear twice in the summand, namelyj
,k
, andl
. As a sum with this property often appears in physics, vector calculus, and probably some other fields, there is a NumPy tool for it, namelyeinsum
.In the above example, you can use it to calculate your matrix product as follows:
Here, the first argument tells the function which indices to apply to the argument matrices and then all doubly appearing indices are summed over, yielding the desired result.
Note that the computational efficiency depends on several factors (so you are probably best off with just testing it):
This might be a relatively recent feature, but I like:
or if you had a long chain you could do:
Update:
There is more info about reduce here. Here is an example that might help.
Update 2016: As of python 3.5, there is a new matrix_multiply symbol,
@
:Resurrecting an old question with an update:
As of November 13, 2014 there is now a
np.linalg.multi_dot
function which does exactly what you want. It also has the benefit of optimizing call order, though that isn't necessary in your case.Note that this available starting with numpy version 1.10.