[英]multiplying 2 2d matrices and get a 3d matrix out
import numpy as np
a = np.array([[1,2],[3,4]])
print(a.shape)
c = np.array([[1,2,3]])
print(c.shape)
#wanted result multiplication of a*c would return 2,2,3 shape matrix
final = np.array([[[1,2,3],[2,4,6]],[[3,6,9],[4,8,12]]])
print(final.shape)
print(final)
我想將兩個不同形狀的矩陣相乘,基本上得到一個 3d 矩陣的結果。 我希望你從代碼中得到模式。 有什么簡單的numpyic方法嗎? 我會很感激。
您可以為此使用 NumPy 廣播:
a[...,None] * c
array([[[ 1, 2, 3],
[ 2, 4, 6]],
[[ 3, 6, 9],
[ 4, 8, 12]]])
以下基本上調整了維度,以便將乘法廣播到所需的輸出形狀:
a[...,None].shape
(2, 2, 1)
試試np.einsum
out = np.einsum('ij,kl->klj',c,a)
Out[35]:
array([[[ 1, 2, 3],
[ 2, 4, 6]],
[[ 3, 6, 9],
[ 4, 8, 12]]])
In [36]: out.shape
Out[36]: (2, 2, 3)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.