New*_*tat 3 python numpy vectorization
我有两个numpy.array
对象x
,y
其中x.shape
is(P, K)
和y.shape
is (T, K)
。我想对这两个对象进行外部求和,以使结果具有 shape (P, T, K)
。我知道np.add.outer
和np.einsum
功能,但我无法让它们执行我想要的操作。
下面给出了预期的结果。
x_plus_y = np.zeros((P, T, K))
for k in range(K):
x_plus_y[:, :, k] = np.add.outer(x[:, k], y[:, k])
Run Code Online (Sandbox Code Playgroud)
但我必须想象有一种更快的方法!
小智 5
一种选择是添加新维度x
并使用 numpy 广播添加:
out = x[:, None] + y
Run Code Online (Sandbox Code Playgroud)
或者正如@FirefoxMetzger 指出的那样,明确的尺寸更具可读性:
out = x[:, None, :] + y[None, :, :]
Run Code Online (Sandbox Code Playgroud)
测试:
P, K, T = np.random.randint(10,30, size=3)
x = np.random.rand(P, K)
y = np.random.rand(T, K)
x_plus_y = np.zeros((P, T, K))
for k in range(K):
x_plus_y[:, :, k] = np.add.outer(x[:, k], y[:, k])
assert (x_plus_y == x[:, None] + y).all()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
136 次 |
最近记录: |