Issue
Assume we have 6 vectors (each vector has 1*4 dimension) in a numpy array having shape (3, 2, 4) like this:
A=np.array([ [[1,2,3,4], [5,6,7,8]], [[ 7,8 ,9,10],[ 11,12 ,13,14]], [[ 15,16 ,17,18],[ 19,20 ,21,22]] ])
Assume we have single Matrix B having dimensions 4*4 in a np.array form having (4, 4) shape as follows
B=np.array([ [1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]])
How to perform matrix multiplication of matrix B to every vector of the 6 vectors in A and the result have the same shape as A the resalut like this
result=np.array([ [[1,2,3,4]@B, [5,6,7,8]@B], [[ 7,8 ,9,10]@B,[ 11,12 ,13,14]@B], [[ 15,16 ,17,18]@B,[ 19,20 ,21,22]@B] ])
result=np.array([[[ 90, 100, 110, 120],
[202, 228, 254, 280]],
[[258, 292, 326, 360],
[370, 420, 470, 520]],
[[482, 548, 614, 680],
[594, 676, 758, 840]]])
Solution
Edit:
It seems you are looking for np.matmul
:
>>> np.matmul(A, B)
array([[[ 90, 100, 110, 120],
[202, 228, 254, 280]],
[[258, 292, 326, 360],
[370, 420, 470, 520]],
[[482, 548, 614, 680],
[594, 676, 758, 840]]])
However, you can probably use numpy broadcasting to get what you expect:
>>> Stu_data[:, :, None] * A_data
array([[[[ 1, 4, 9, 16],
[ 5, 12, 21, 32],
[ 9, 20, 33, 48],
[ 13, 28, 45, 64]],
[[ 55, 132, 231, 352],
[ 275, 396, 539, 704],
[ 495, 660, 847, 1056],
[ 715, 924, 1155, 1408]]],
[[[ 1, 4, 9, 16],
[ 5, 12, 21, 32],
[ 9, 20, 33, 48],
[ 13, 28, 45, 64]],
[[ 1, 4, 9, 16],
[ 5, 12, 21, 32],
[ 9, 20, 33, 48],
[ 13, 28, 45, 64]]],
[[[ 1, 4, 9, 16],
[ 5, 12, 21, 32],
[ 9, 20, 33, 48],
[ 13, 28, 45, 64]],
[[ 1, 4, 9, 16],
[ 5, 12, 21, 32],
[ 9, 20, 33, 48],
[ 13, 28, 45, 64]]]])
Shapes:
>>> A_data
(4, 4)
>>> Stu_data
(3, 2, 4)
>>> Stu_data[:, :, None].shape
(3, 2, 1, 4)
>>> (Stu_data[:, :, None] * A_data).shape
(3, 2, 4, 4)
Answered By - Corralien
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.