python怎么做多个矩阵_python – 从具有多个结果的矩阵构建一个映射

我有一个输入矩阵,其n x m维未知,由1和0填充

例如,一个5×4矩阵:

A = array(

[[1, 0, 0, 0],

[1, 0, 0, 0],

[0, 1, 1, 0],

[0, 1, 1, 0],

[1, 0, 1, 1]])

目标

我需要在尽可能多的列和行之间创建1:1映射,其中该位置的元素为1.

我所说的1:1地图的意思是每列和每行最多可以使用一次.

理想的解决方案具有最多的映射,即.使用的行和列最多.它还应避免使用较大矩阵不能很好地扩展的详尽组合或操作(实际上,最大尺寸应为100×100,但没有声明的限制,因此它们可以更高)

这是上述可能的结果

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

[ 0., 0., 0., 0.],

[ 0., 0., 1., 0.],

[ 0., 1., 0., 0.],

[ 0., 0., 0., 1.]])

更多示例:

input:

0 1 1

0 1 0

0 1 1

output (one of several possible ones):

0 0 1

0 1 0

0 0 0

另一个(这表明可能出现一个问题)

input:

0 1 1 1

0 1 0 0

1 1 0 0

a good output (again, one of several):

0 0 1 0

0 1 0 0

1 0 0 0

a bad output (still valid, but has fewer mappings)

0 1 0 0

0 0 0 0

1 0 0 0

更好地展示他们如何成为多个输出

input:

0 1 1

1 1 0

one possible output:

0 1 0

1 0 0

a second possible output:

0 0 1

0 1 0

a third possible output

0 0 1

1 0 0

我做了什么?

我现在有一种非常愚蠢的处理方式,但根本无法保证工作.基本上我只是用单位矩阵构建一个滤波器矩阵(因为它是完美的映射,每一行和每一列都使用一次)然后我随机交换它的列(n次)并用它过滤原始矩阵,记录过滤器具有最佳结果的矩阵.

My [non] solution:

import random

import numpy as np

# this is a starting matrix with random values

A = np.array(

[[1, 0, 0, 0],

[1, 0, 0, 0],

[0, 1, 1, 0],

[0, 1, 1, 0],

[1, 0, 1, 1]])

# add dummy row to make it square

new_col = np.zeros([5,1]) + 1

A = np.append(A, new_col, axis=1)

# make an identity matrix (the perfect map)

imatrix = np.diag([1]*5)

# randomly swap columns on the identity matrix until they match.

n = 1000

# this will hold the map that works the best

best_map_so_far = np.zeros([1,1])

for i in range(n):

a, b = random.sample(range(5), 2)

t = imatrix[:,a].copy()

imatrix[:,a] = imatrix[:,b]

imatrix[:,b] = t

# is this map better than the previous best?

if sum(sum(imatrix * A)) > sum(sum(best_map_so_far)):

best_map_so_far = imatrix

# could it be? a perfect map??

if sum(sum(imatrix * A)) == A.shape[0]:

break

# jk.

# did we still fail

if sum(sum(imatrix * A)) != 5:

print('haha')

# drop the dummy row

output = imatrix * A

output[:,:-1]

#... wow. it actually kind of works.

解决方法:

这个怎么样?

let S be the solution vector, as wide as A, containing row numbers.

let Z be a vector containing the number of zeros in each column.

for each row:

select the cells which contain 1 in A and no value in S.

select from those cells those with the highest score in Z.

select from those cells the first (or a random) cell.

store the row number in the column of S corresponding to the cell.

这会给你一个充分的解决方案吗?如果是这样,它应该比你拥有的效率更高.

标签:python,algorithm,math,numpy

来源: https://codeday.me/bug/20190701/1349777.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值