我必须最小化一个相当复杂的函数。为了实现最小化,我使用了Extreme Optimization Library中的NonLinearProgram。因为没有办法找到全局最小值,所以我使用不同的起点,然后选择“最佳最小值”。我的问题是可能会有一些起点,评估可能需要很长时间。在F#中有没有一些通用的方法,或者在极端优化中有一些特殊的方法,比如在10分钟后停止评估,然后用nan返回一个列表?
let funcFindPara (startpoint:float list) func =
let nlp = new NonlinearProgram(6)
// add the function
nlp.ObjectiveFunction <- (fun x -> func x.[0] x.[1] x.[2] x.[3] x.[4] x.[5])
// add lineare constraints
nlp.AddLinearConstraint("a + d > 0", Vector.Create(1.0, 0.0, 0.0, 1.0, 0.0, 0.0), 1.0e-5, infinity) |> ignore
nlp.AddLinearConstraint("c > 0", Vector.Create(0.0, 0.0, 1.0, 0.0, 0.0, 0.0), 1.0e-5, infinity) |> ignore
nlp.AddLinearConstraint("d > 0", Vector.Create(0.0, 0.0, 0.0, 1.0, 0.0, 0.0), 1.0e-5, infinity) |> ignore
nlp.AddLinearConstraint("gamma > 0", Vector.Create(0.0, 0.0, 0.0, 0.0, 1.0, 0.0), 1.0e-5, infinity) |> ignore
nlp.AddLinearConstraint("0 < rho_infty <= 1", Vector.Create(0.0, 0.0, 0.0, 0.0, 0.0, 1.0), 1.0e-5, 1.0) |> ignore
// add nonlinear constrains
// gamma <= -ln(rho_infty)
nlp.AddNonlinearConstraint((fun (x : Vector) -> x.[4] + log(x.[5])), ConstraintType.LessThanOrEqual, 0.0, (fun (x : Vector) -> fun (y : Vector) ->
y.[0] <- 0.0
y.[1] <- 0.0
y.[2] <- 0.0
y.[3] <- 0.0
y.[4] <- 1.0
y.[5] <- 1.0 / x.[5]
y
)
) |> ignore
// add starting point
nlp.InitialGuess <- Vector.Create(startpoint.[0], startpoint.[1], startpoint.[2], startpoint.[3], startpoint.[4], startpoint.[5])
// solve
let solution = nlp.Solve()
// return list with parameters
List.init 6 (fun index -> solution.[index])发布于 2014-04-15 03:39:09
您可以使用async { }包装函数,并将其与超时一起传递给RunSynchronously:
let withTimeout f timeout defaultValue =
try Async.RunSynchronously((async { return f() }), timeout)
with :? System.TimeoutException -> defaultValue
let longFn() =
System.Threading.Thread.Sleep(5000)
[1.0; 2.0; 3.0]
//Usage
withTimeout longFn 2000 [nan; nan; nan]https://stackoverflow.com/questions/23063187
复制相似问题