假设我有一个这样的数组:
from skopt.space import Space
from skopt.sampler import Lhs
import numpy as np
np.random.seed(42)
rows = 5
cols = 3
dummy = np.zeros((rows, cols))
array([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])现在,我想使用skopt.Lhs.generate用一个1填充这个数组的某些位置,从而排除存储在ignore中的某些位置
ignore = np.array([
[3, 1],
[4, 1]
])我怎样才能做到最好呢?
我能做到
space = Space([(0, rows - 1), (0, cols - 1)])
lhs = Lhs(criterion="maximin", iterations=1000)
lh = np.array(lhs.generate(space.dimensions, 3))
dummy[lh[:, 0], lh[:, 1]] = 1这给了我们
array([[0., 0., 1.],
[1., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 1., 0.]])但正如人们可以看到的那样,4, 1被占据了,但它不应该被占据。
一种方法是将lhs.generate调用放在一个while循环中,然后总是检查ignore中是否有任何元素,但我想知道是否有更直接的解决方案。
发布于 2021-02-07 20:28:02
为了完整起见,使用while循环的解决方案可能如下所示:
from skopt.space import Space
from skopt.sampler import Lhs
import numpy as np
def contains_element(a, b):
return any(li in a for li in b)
np.random.seed(42)
rows = 5
cols = 3
dummy = np.zeros((rows, cols))
ignore = [
[3, 1],
[4, 1]
]
space = Space([(0, rows - 1), (0, cols - 1)])
contains_row = True
while contains_row:
lhs = Lhs(criterion="maximin", iterations=1000)
lh = lhs.generate(space.dimensions, 3)
contains_row = contains_element(lh, ignore)
print(lh)
print(contains_row)
print('-----------------------\n')
lh = np.array(lh)
dummy[lh[:, 0], lh[:, 1]] = 1
print(dummy)哪种打印
[[2, 0], [0, 2], [4, 1]]
True
-----------------------
[[2, 0], [1, 2], [4, 1]]
True
-----------------------
[[4, 2], [0, 1], [2, 0]]
False
-----------------------
[[0. 1. 0.]
[0. 0. 0.]
[1. 0. 0.]
[0. 0. 0.]
[0. 0. 1.]]因此,这里需要3次迭代,直到找到不在ignore中的位置。如果有人知道更直接的解决方案,请让我知道!
https://stackoverflow.com/questions/66082989
复制相似问题