创建置换矩阵 - numpy
问题描述:
给定一个整数k
我将如何创建一个置换矩阵,其中包含序列1
到k
的所有可能的置换?例如,我们考虑k=2
。然后我想创建矩阵:创建置换矩阵 - numpy
1 2
2 1
和k=3
:
1 1 2 2 3 3
2 3 1 3 1 2
3 2 3 1 2 1
我使用numpy.random.permutation
但这只能产生一个单一的排列试过。所以,我可以继续使用这个函数,附加唯一的排列,直到列数等于k!
,但这看起来效率非常低。
答
基于关闭this answer:
import numpy as np
import itertools as it
import math
def myPerms(k):
f_k=math.factorial(k)
A=np.empty((k,f_k))
for i,perm in enumerate(it.permutations(range(k))):
A[:,i] = perm
A+=1
return A
print(myPerms(3))
#[[ 1. 1. 2. 2. 3. 3.]
# [ 2. 3. 1. 3. 1. 2.]
# [ 3. 2. 3. 1. 2. 1.]]
答
怎么样纯numpy的解决方案:
from math import factorial as fac
import numpy as np
def permmat(n):
if n==1:
return np.array([[1]], dtype=np.int8)
fnm1 = fac(n-1)
pmat_nm1 = permmat(n-1)
pmat = np.empty((n, fac(n)), dtype=np.int8)
pmat[0] = np.repeat(np.arange(n,0,-1), fnm1)
pmat[1:, :fnm1] = pmat_nm1
for i in range(1,n):
view = pmat[1:, fnm1*i:fnm1*(i+1)]
view[:,:] = pmat_nm1
view[pmat_nm1==(n-i)] = n
return pmat
print(permmat(4))
输出:
[[4 4 4 4 4 4 3 3 3 3 3 3 2 2 2 2 2 2 1 1 1 1 1 1]
[3 3 2 2 1 1 4 4 2 2 1 1 3 3 4 4 1 1 3 3 2 2 4 4]
[2 1 3 1 2 3 2 1 4 1 2 4 4 1 3 1 4 3 2 4 3 4 2 3]
[1 2 1 3 3 2 1 2 1 4 4 2 1 4 1 3 3 4 4 2 4 3 3 2]]
目前仍然对一些性能黑客空间,但我太懒惰写他们。
答
我的解决方案:
perm_mat = np.zeros(PERM_SIZE,NUM_OF_PERM))
for i in range(NUM_OF_PERM):
perm_mat[:,i] = np.random.permutation(PERM_SIZE))
perm_mat = perm_mat.astype(int)
怎么样喂养'itertools.permutations'成numpy的阵列? –
@YakymPirozhenko是否可以在不导入'itertools'的情况下做到这一点? – Apollo
好吧,除非你想编写自己的函数来生成一个排列列表。另外,由于'itertools'是一个内置模块,除非你有一些明确的限制,否则我看不到导入的很多缺点。 –