【问题标题】:Generating one hot matrices of all possible combinations of two lists?生成两个列表的所有可能组合的一个热矩阵?
【发布时间】:2021-01-13 19:14:27
【问题描述】:

假设我有一个矩阵(数组),其中元素位于集合 {0,1} 中,受所有行和列总和为 1 的约束。

matches = np.array([[0,0,1],
                    [1,0,0],
                    [0,1,0]])

有没有办法生成满足上述约束的所有可能的此类矩阵?

这是一个天真的尝试,从一个模糊相关的question/answer 中汲取灵感,

import itertools

a = ['A','B','C']
b = ['X','Y','Z']

def get_permutations(a,b):
  index_map = {val:idx for idx,val in enumerate(a)}
  index_map.update({val:idx for idx,val in enumerate(b)})
  
  perms = [list(zip(x,b)) for x in itertools.permutations(a,len(b))]
  possible = []
  for p in perms: 
    temp_arr = np.zeros([len(a),len(b)])    
    for tup in p:
      x,y = index_map[tup[0]], index_map[tup[1]]
      temp_arr[x,y] = 1
    possible.append(temp_arr)
  return possible 


get_permutations(a,b) 

>>>
[array([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.]]), array([[1., 0., 0.],
        [0., 0., 1.],
        [0., 1., 0.]]), array([[0., 1., 0.],
        [1., 0., 0.],
        [0., 0., 1.]]), array([[0., 0., 1.],
        [1., 0., 0.],
        [0., 1., 0.]]), array([[0., 1., 0.],
        [0., 0., 1.],
        [1., 0., 0.]]), array([[0., 0., 1.],
        [0., 1., 0.],
        [1., 0., 0.]])]

我的问题是:是否有更简洁或更快的方法来返回满足上述约束的数组列表?

【问题讨论】:

    标签: python arrays matrix combinations permutation


    【解决方案1】:

    您的解决方案似乎很快,可以纠正的事情并不多。 这是我想出的

    import itertools
    import numpy as np
    
    a = ['A','B','C']
    b = ['X','Y','Z']
    
    def get_permutations(a,b):
        n = len(a)
        possible = []
        for perm in itertools.permutations(range(n), n):
            matrix = np.zeros([n, n])
            i = 0
            for j in perm:
                matrix[i, j] = 1
                i += 1
            possible.append(matrix)
        return possible
    
    get_permutations(a,b)
    

    您的答案平均需要 3.17784857749939e-05 秒,而我的答案平均需要 9.6732497215271e-06 秒(10000 个测试样本)。差别真的很小,但如果你真的需要最快的解决方案,请考虑这个。

    确实最慢的部分是itertools.permuatations(),但我还没有找到具有相当速度冒险的替代方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-01
      • 1970-01-01
      • 2018-08-01
      • 2014-10-27
      • 2014-06-06
      • 2018-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多