首页 > 解决方案 > 可以限制 skopt.Lhs.generate 的结果吗?

问题描述

假设我有一个这样的数组:

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但我想知道是否有更直接的解决方案。

标签: pythonstatisticsskopt

解决方案


为了完整起见,使用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. 如果有人知道更简单的解决方案,请告诉我!


推荐阅读