![](/img/trans.png)
[英]Numpy: getting a list of combinations of ratios such that they all add to 1
[英]Numpy Add All Combinations of Vectors
添加两个向量 arrays 的所有组合的最有效的数值方法是什么? 例如,我想要的是以下内容:
a = np.array([[1,2,3], [4,5,6]])
b = np.array([[7,8,9], [10,11,12]])
[ai + bj for ai in a for bj in b]
给
[array([ 8, 10, 12]),
array([11, 13, 15]),
array([11, 13, 15]),
array([14, 16, 18])]
它是一个带有向量而不是主要数据类型的网格。
我已经尝试过明确地构建网格结果,这比列表理解要快:
a_tile = np.tile(a, (2, 1))
array([[1, 2, 3],
[4, 5, 6],
[1, 2, 3],
[4, 5, 6]])
b_repeat = np.repeat(b, 2, axis=0)
array([[ 7, 8, 9],
[ 7, 8, 9],
[10, 11, 12],
[10, 11, 12]])
a_tile + b_repeat
array([[ 8, 10, 12],
[11, 13, 15],
[11, 13, 15],
[14, 16, 18]])
这是最有效的吗? 我正在寻找一种广播 arrays 的方法,以便不明确构建网格。
您可以使用numpy.broadcast_to广播数组
N = 2 #number of repeats
your_req_array = np.broadcast_to(b.T, (N,b.shape[1], b.shape[0])).transpose(2,0,1).reshape(-1,b.shape[1]) + np.broadcast_to(a, (N,a.shape[0], a.shape[1])).reshape(-1,b.shape[1])
您可以尝试以下方法:
import numpy as np
a = np.array([[1,2,3], [4,5,6]])
b = np.array([[7,8,9], [10,11,12]])
(a[..., None] + b.T).transpose(0, 2, 1).reshape(-1, 3)
它给:
array([[ 8, 10, 12],
[11, 13, 15],
[11, 13, 15],
[14, 16, 18]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.