Numpy:将最终维度的切片与另一个数组相乘

huangapple go评论81阅读模式
英文:

Numpy: multiply slices of final dimension by another array

问题

我有一个维度为(N, M)的数组x和一个维度为(N, M, 2)的数组y。对于任何i, j,我想将y[i, j, :]的每个元素乘以x[i, j]。我应该如何做到这一点?

import numpy as np
x = np.random.randn(100, 10)
y = np.random.randn(100, 10, 2)
x * y # 这不起作用
英文:

I have an array x of dimension (N, M) and an array y of dimension (N, M, 2). For any i, j I would like to multiply each y[i, j, :] by x[i, j]. How can I do this?

import numpy as np
x = np.random.randn(100, 10)
y = np.random.randn(100, 10, 2)
x * y # this does not work

答案1

得分: 1

Add extra dim as follows:

import numpy as np
x = np.random.randn(100, 10)
print(x[..., None].shape)
y = np.random.randn(100, 10, 2)
x[..., None] * y
英文:

Add extra dim as follows:

import numpy as np
x = np.random.randn(100, 10)
print(x[..., None].shape)
y = np.random.randn(100, 10, 2)
x[..., None] * y  

huangapple
  • 本文由 发表于 2023年5月10日 22:59:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76219942.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定