python - 可以限制 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
但我想知道是否有更直接的解决方案。
解决方案
为了完整起见,使用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
. 如果有人知道更简单的解决方案,请告诉我!
推荐阅读
- sql-server - SQL Server 典型转置
- python - 与 anaconda 和 python 库相关的问题
- android - RecyclerView android中的内存泄漏
- javascript - 为什么 `this.$axios.$get(...)` 在 nuxt.js 存储中不起作用?
- python - 在 swarmplot 上绘制另一个点
- r - 为什么用 ggplot2 绘图时breaks_width 会偏移我的数据?
- go - 如何为我的 Golang 服务器分配域名?
- python - 如何将 pandas DataFrame 绘制为没有索引列的表?
- sockets - 如何从 TCP 套接字服务器读取所有数据并随后执行操作
- c - 如何在 Rust 中正确包装 C 函数指针?