在特定索引处设置高维 numpy 数组等于一维数组

问题描述 投票:0回答:1

我有一组对称张量

full_tensors
,并计算了二维数组
tensor_reduced
中的所有不同元素。我想根据不同元素
full_tensors
计算完整的
tensor_reduced
。我有一个列表
all_permutations_list
,其中包含应具有相同值的所有索引的元组(例如
all_permutations_list[1]=((0, 0, 1, 0, 0, 0), (0, 1, 0, 0, 0, 0), (1, 0, 0, 0, 0, 0), (0, 0, 0, 1, 0, 0), (0, 0, 0, 0, 1, 0), (0, 0, 0, 0, 0, 1)
),并且
tensor_reduced.shape[1]
len(all_permutations_list)
相同。

以下代码可以实现我想要的功能:

def makeFulltensor(tensor_reduced,all_permutations_list,dim=4):
       full_tensors=np.zeros((tensor_reduced.shape[0],dim,dim,dim,dim,dim,dim),dtype=tensor_reduced.dtype)
       for index,all_permutations in enumerate(all_permutations_list):
            for perm in (all_permutations):
                 full_tensors[:,perm[0],perm[1],perm[2],perm[3],perm[4],perm[5]]=tensor_reduced[:,index]
       return full_tensors

我想使用 NumPy 的索引功能来加速它,以避免内部(也许还有外部)for 循环。有谁知道有效的方法吗?

谢谢!

PS:all_permutations_list计算如下:

from itertools import permutations
from itertools import combinations_with_replacement as cwr
all_permutations_list=[]
reduced_indices=list(cwr(range(4), 6))
for index,(i,j,k,l,m,n) in enumerate(reduced_indices):
     all_permutations=set(permutations([i,j,k,l,m,n]))
     all_permutations_list.append(all_permutations)
all_permutations_list=[tuple(x) for x in all_permutations_list]
python arrays numpy tensor
1个回答
0
投票

如果你想避免内部循环,请使用NumPy的高级索引功能:

def makeFulltensor(tensor_reduced, all_permutations_list, dim=4):
    full_tensors = np.zeros((tensor_reduced.shape[0], dim, dim, dim, dim, dim, dim), dtype=tensor_reduced.dtype)
    for index, all_permutations in enumerate(all_permutations_list):
        full_tensors[:, all_permutations] = tensor_reduced[:, index, None]
    return full_tensors

假设

all_permutations_list
是 NumPy 数组的元组列表。如果不是,您必须首先将其转换:

all_permutations_list = [np.array(x) for x in all_permutations_list]
© www.soinside.com 2019 - 2024. All rights reserved.