【发布时间】:2018-06-25 10:27:51
【问题描述】:
我正在尝试找到一种优雅的方法来解决以下问题。
我有一个张量y 包含n dxd 矩阵,我通过选择矩阵X 的行组合获得它。我有第二个 numpy 数组,大小为k x d。我的意图是扩展张量,以便将k x d 矩阵的每一行添加到 y 张量中的每个元素,以获得带有k x nd x (d+1) 矩阵的y' 张量。
如果没有 for 循环,我看不到怎么做。我的简单代码示例如下:
#Array x
X = np.arange(27).reshape(9,3)
# Create tensor y
combs = [(0,1,2),(0,1,3),(0,1,4),(0,1,5)]
y = X[combs,:]
# Add a dummy column of 1.0s to each element of the y tensor
b = np.array([1.0,1.0,1.0]).reshape(1,3)
b = b.repeat(y.shape[0],axis=0).reshape(y.shape[0],y.shape[1],1)
# Concatenate the column with the tensor
y_new = np.concatenate((y,b),axis=2)`
这个解决方案远非理想,因为我必须保留原始数组的副本,遍历所有行,获取 k 张量,然后在最后合并它们。在我试图解决的一般问题中,张量 y 很大,并且多个进程并行执行,因此这种张量扩展在理想情况下应该尽可能高效。任何建议表示赞赏!
【问题讨论】: