【问题标题】:How to do basic optimisation using loco如何使用 loco 进行基本优化
【发布时间】:2017-12-10 19:06:47
【问题描述】:

我正在尝试使用loco 做一个基本的优化示例。

我有一个成本向量,其索引对应于多个插槽的整数值,并且希望最小化插槽的不同子集的成本总和。

请在下面查看我的尝试,该尝试失败,因为选择的插槽与成本之间没有“联系”。

(def costs [10 10 20 20 30 30 40 40 10 10])

(let [slot-vars (for [i (range 5)] ($in [:slot i] 1 10))
      cost-vars (for [i (range 10)] ($in [:cost i] 10 40))]
  (solution
   (concat
    slot-vars
    cost-vars
    [($distinct (for [i (range 5)] [:slot i]))]
    (for [i (range 5)]
      ($= [:cost i] (get costs i))))
   :minimize (apply $+ (for [i (range 5)] [:slot i]))))

【问题讨论】:

  • 这听起来像是一个最小化背包问题。你可以做一个最大化,但不能做一个最小化。可能必须直接与 choco 库打交道才能做到这一点。

标签: optimization clojure constraint-programming


【解决方案1】:

首先,我不完全确定我理解这个问题的重点,因为显然解决方案是只取列表中的 5 个最小值。但是如果你想让 loco 这样做,我同意背包约束是一个方便的工具。与迈克在评论中所说的相反,我认为使用背包进行最小化没有任何障碍。让权重都为 1,并强制权重加起来为 5,以便从 10 个插槽中选择 5 个。我使用变量[:include i] 来指示槽i 是否应该包含在子集中(1 表示真,0 表示假)。我们希望最小化 :include 变量的向量和成本向量的点积。

(def costs [10 10 20 20 30 30 40 40 10 10])
(def weights (repeat 10 1))

(def include-vars (for [i (range 10)] [:include i]))
(def include-constraints (for [i (range 10)] ($in [:include i] 0 1)))

(def model
  (concat
   include-constraints
   [($knapsack weights costs include-vars 5 :total)
    ($in :total 0 (apply + costs))]))

(solution model :minimize :total)

结果是:

{[:include 4] 0, [:include 6] 0, [:include 9] 1, [:include 1] 1, [:include 3] 0, [:include 8] 1, :total 60, [:include 0] 1, [:include 7] 0, [:include 2] 1, [:include 5] 0}

【讨论】:

  • 感谢您的回答。该示例只是说明性的,在我的实际用例中,变量将受到许多其他约束。
【解决方案2】:

这不是答案,但我希望它可能有助于指出一个可能有帮助的方向。听起来像是背包问题?

您可以通过以下方式找到最大值:

(def slots (for [i (range 10)] (keyword (str "slot-" i))))

(solution
   (concat
    (for [s slots] ($in s 0 1))
    [($in :total-weight 10 60)
     ($in :total-value 5 5)
     ($knapsack [10 10 20 20 30 30 40 40 10 10]
                (repeat 10 1)
                slots :total-weight :total-value)]))

假设你只能有 5 个插槽。

是否可以通过查看源代码并直接使用 Choco 库来编写一个最小化版本?

检查 loco knapsack 函数的来源。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 2014-11-05
    • 1970-01-01
    • 2021-07-17
    • 2017-05-27
    • 2015-08-01
    • 2018-01-19
    相关资源
    最近更新 更多