2D numpy中的所有组合
我正在尝试在下面的问题中修改希尔伯茨提供的答案代码,以允许其用于多个值,而不仅仅是二进制值。 2D numpy中的所有二进制组合
因此,而不是仅允许0和1一样,在上一个示例中,我希望找到所有组合,而无需旋转0、1、2和3之类的数据。
我以这种方式对其进行了修改,主要将原始代码中的“ 2”替换为变量,并试图用变量“ M”替换它以遵循初始公式。但是我认为这里的问题与数据“ bitwise_and”的数字类型有关。有人对什么是问题或提示有任何建议吗?
def get_binary_mats(n,m):
# all possible n by n binary matrices up to rotation:
bin_mats = (np.bitwise_and(np.arange(m**(n*n))[:,None], m ** np.arange(n*n)) > 0)\
.reshape(-1, n, n)
# define a score for each matrix based on position of ones
score = m ** np.arange(n*n).reshape(n,n)
# array([[ 1, 2, 4],
# [ 8, 16, 32],
# [ 64, 128, 256]])
score_arr = np.stack([np.rot90(score, k=k) for k in range(4)])
# array([[[ 1, 2, 4],
# [ 8, 16, 32],
# [ 64, 128, 256]],
# [[ 4, 32, 256],
# [ 2, 16, 128],
# [ 1, 8, 64]],
# [[256, 128, 64],
# [ 32, 16, 8],
# [ 4, 2, 1]],
# [[ 64, 8, 1],
# [128, 16, 2],
# [256, 32, 4]]])
scores = np.einsum("ijk,ljk->il", bin_mats, score_arr)
_, idx = np.unique(scores.min(1), return_index=True)
return bin_mats[idx,...]
谢谢
I am trying to modify the code provided as answer by Hilberts in below question to allow it for multiple values and not only binary.
All binary combinations in a 2d Numpy
So, rather than only allow 0 and 1 like in the previous example, i would like find all combinations without rotations for data like 0, 1, 2 and 3 .
I modified it in this way, mainly replacing the "2" in the original code by a variable and tried to replace it by the variable "m" to follow the initial formula. But I think the issue here is related to the numpy type of data "bitwise_and" . Does anyone have any advices about what would be problem or any hint?
def get_binary_mats(n,m):
# all possible n by n binary matrices up to rotation:
bin_mats = (np.bitwise_and(np.arange(m**(n*n))[:,None], m ** np.arange(n*n)) > 0)\
.reshape(-1, n, n)
# define a score for each matrix based on position of ones
score = m ** np.arange(n*n).reshape(n,n)
# array([[ 1, 2, 4],
# [ 8, 16, 32],
# [ 64, 128, 256]])
score_arr = np.stack([np.rot90(score, k=k) for k in range(4)])
# array([[[ 1, 2, 4],
# [ 8, 16, 32],
# [ 64, 128, 256]],
# [[ 4, 32, 256],
# [ 2, 16, 128],
# [ 1, 8, 64]],
# [[256, 128, 64],
# [ 32, 16, 8],
# [ 4, 2, 1]],
# [[ 64, 8, 1],
# [128, 16, 2],
# [256, 32, 4]]])
scores = np.einsum("ijk,ljk->il", bin_mats, score_arr)
_, idx = np.unique(scores.min(1), return_index=True)
return bin_mats[idx,...]
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)