Hi, I want to compute the following dot product: P = np.array( [[ p11, p12 ], [p21, p22]] ) C = np.array( [c1, c2] ) where c1 and c2 are m*m matrices, so that C.shape = (2,m,m) I want to compute: A = np.array([a1, a2]) where a1 and a2 are two matrices m*m, from the dot product of P and C. I would expect: a1 = p11*c1 + p12*c2 a2 = p21*c1 + p22*c2 The code should be general so that i can multiply any P and C with shapes: P.shape = (n, n) C.shape = (n, m, l) and with a result as: A.shape = (n, m, l) I had a look at np.dot? but i can't sort out how to transpose/reshape the C array. Any help is greatly appreciated. Ciao
On Wed, Feb 9, 2011 at 9:53 AM, Davide Lasagna <davide.lasagna@polito.it>wrote:
Hi,
I want to compute the following dot product:
P = np.array( [[ p11, p12 ], [p21, p22]] ) C = np.array( [c1, c2] )
where c1 and c2 are m*m matrices, so that
C.shape = (2,m,m)
I want to compute:
A = np.array([a1, a2])
where a1 and a2 are two matrices m*m, from the dot product of P and C.
I would expect:
a1 = p11*c1 + p12*c2 a2 = p21*c1 + p22*c2
The code should be general so that i can multiply any P and C with shapes:
P.shape = (n, n) C.shape = (n, m, l)
and with a result as:
A.shape = (n, m, l)
I had a look at np.dot? but i can't sort out how to transpose/reshape the C array.
Any help is greatly appreciated.
Ciao
tensordot() should do the trick. A = np.tensordot(P, C, axes=1) Ben Root
2011/2/9 Davide Lasagna <davide.lasagna@polito.it>:
Hi,
I want to compute the following dot product:
P = np.array( [[ p11, p12 ], [p21, p22]] ) C = np.array( [c1, c2] )
a1 = p11*c1 + p12*c2 a2 = p21*c1 + p22*c2
P.shape = (n, n) C.shape = (n, m, l)
and with a result as:
A.shape = (n, m, l)
Interesting problem. So: A[i, j, k] = \sum_q P[i, q] * C[q, j, k] Your problem description is an interesting way to look at tensordot. Normally the sum character is emphasised, but in your description the indiced not summed over play the role of forming complete matrices which are multiplied by scalars. Alternatively, you can look at your tensordot as a (m, l) matrix of (n,) vectors which originate from dot-multiplying earch (n,) vector in a (m, l) matrix, which comprises C, with the P matrix. But this is just an interpretation, I like the equation above best of them all. Ben's suggestion is identical to: A = numpy.tensordot(P, C, axes=(1, 0)) Depends on what you want to emphasis, the concrete indices or how many of the last/first indices to take in. http://docs.scipy.org/doc/numpy/reference/generated/numpy.tensordot.html Friedrich
Ben's suggestion is identical to:
A = numpy.tensordot(P, C, axes=(1, 0))
Yes, that does the trick! Thank, very good idea. Since i've build atlas with threading support, in the computation of the dot product all four cpus go to 100%, which makes it quite fast. I'm starting to love numpy array facilities.... Ciao Davide
participants (3)
-
Benjamin Root -
Davide Lasagna -
Friedrich Romstedt