[英]How to distribute a Numpy array along the diagonal of an array of higher dimension?
我有三個二維 Numpy arrays x
, w
, d
並想創建第四個稱為a
。 w
和d
僅用d.shape + w.shape
定義a
的形狀。 我想在 a 的條目中a
x
在其他地方有一個零。 具體來說,我想要這個代碼的無循環版本:
a = np.zeros(d.shape + w.shape)
for j in range(d.shape[1]):
a[:,j,:,j] = x
例如,給定:
x = np.array([
[2, 3],
[1, 1],
[8,10],
[0, 1]
])
w = np.array([
[ 0, 1, 1],
[-1,-2, 1]
])
d = np.matmul(x,w)
我想a
array([[[[ 2., 0., 0.],
[ 3., 0., 0.]],
[[ 0., 2., 0.],
[ 0., 3., 0.]],
[[ 0., 0., 2.],
[ 0., 0., 3.]]],
[[[ 1., 0., 0.],
[ 1., 0., 0.]],
[[ 0., 1., 0.],
[ 0., 1., 0.]],
[[ 0., 0., 1.],
[ 0., 0., 1.]]],
[[[ 8., 0., 0.],
[10., 0., 0.]],
[[ 0., 8., 0.],
[ 0., 10., 0.]],
[[ 0., 0., 8.],
[ 0., 0., 10.]]],
[[[ 0., 0., 0.],
[ 1., 0., 0.]],
[[ 0., 0., 0.],
[ 0., 1., 0.]],
[[ 0., 0., 0.],
[ 0., 0., 1.]]]])
這個答案啟發了以下解決方案:
# shape a: (4, 3, 2, 3)
# shape x: (4, 2)
a = np.zeros(d.shape + w.shape)
a[:, np.arange(a.shape[1]), :, np.arange(a.shape[3])] = x
它使用 Numpy 的廣播(參見此處或 此處)與Advanced Indexing結合來放大x
以適應切片。
我碰巧有一個更簡單的解決方案: a = np.tensordot(x, np.identity(3), axes = 0).swapaxes(1,2)
單位矩陣的大小將取決於您希望重復x
元素的次數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.