我正在尝试使用scipy.optimize.minimize简单的a <= x <= b边界。但是,经常发生我的目标函数在边界之外进行评估。据我了解,当minimize试图确定边界处目标函数的梯度时会发生这种情况。
最小的例子:
import math
import numpy as np
from scipy.optimize import Bounds, minimize
constraint = Bounds([-1, -1], [1, 1], True)
def fun(x):
print(x)
return -math.exp(-np.dot(x,x))
result = minimize(fun, [-1, -1], bounds=constraint)
Run Code Online (Sandbox Code Playgroud)
输出显示最小化器跳转到该点[1,1],然后尝试在 处求值[1.00000001, 1]:
[-1. -1.]
[-0.99999999 -1. ]
[-1. -0.99999999]
[-0.72932943 -0.72932943]
[-0.72932942 -0.72932943]
[-0.72932943 -0.72932942]
[-0.22590689 -0.22590689]
[-0.22590688 -0.22590689]
[-0.22590689 -0.22590688]
[1. 1.]
[1.00000001 1. ]
[1. 1.00000001]
[-0.03437328 -0.03437328]
...
Run Code Online (Sandbox Code Playgroud)
当然,在这个例子中没有问题,因为fun也可以在那里评估。但情况可能并非总是如此...... …
我有以下情况:
我已经在 Scala 中编码了一段时间,在那里我会写一些类似的东西
abstract class Action
case class RenameAction(id: Int, newTitle: String) extends Action
case class StartAction(time: Instant) extends Action
Run Code Online (Sandbox Code Playgroud)
这样我就可以编写类似的函数
def process(action: Action) = action match {
case RenameAction(id, title) => ...
case StartAction(time) => ...
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:在 C# 中解决这个问题的最佳实践/最惯用的方法是什么?
我将描述一些我的想法:
第一种可能性:直接翻译
public abstract class Action
{
}
public sealed class RenameAction : Action
{
public readonly int id;
public readonly string title;
public RenameAction(int …Run Code Online (Sandbox Code Playgroud)