gpt4 book ai didi

r - R 中函数的优化(L-BFGS-B 需要 'fn' 的有限值)

转载 作者:行者123 更新时间:2023-12-04 14:34:56 25 4
gpt4 key购买 nike

我想优化(最大)以下函数 f1 .我编写了以下使用下限和上限的代码,因为我们知道我们所有的参数都等于或大于零,而且我们总是应该有 x4值小于或等于 x6 .如何在 R 中解决此问题?我想获得函数的有限最大值 f1 .

          x1 = 0.1
x2 = 0.1
x3 = 2
x4 = 10
x5 = 2
x6 = 30
x7 = 1
par = list(x1=x1, x2=x2, x3=x3, x4=x4,x5=x5, x6=x6, x7=x7)
par1 = c(1, 1, 2, 1.5, 1, 1.5, 1)

f1 = function(x, par){
sum(log(exp(-(par$x7)*(par$x1*x + par$x2*x^2/2 +
par$x3 * (par$x4-x)^3/3+par$x5 *(x-par$x6)^3/3))))
}

x = seq(0, 500, length=100)
z = c(par$x1, par$x2, par$x3, par$x4, par$x5, par$x6, par$x7)

f2 = function(z){
par.new = list(x1 = z[1], x2 = z[2], x3 = z[3], x4 = z[4]
, x5 = z[5], x6 = z[6], x7 = z[7])
f1(x, par.new)
}

optim(par1, f2, method = "L-BFGS-B", lower = rep(0, length(z)),
upper = rep(Inf,length(z)),control = list(trace = 5,fnscale=-1))
> optim(par1, f2, method = "L-BFGS-B", lower = rep(0, length(z)),
upper = rep(Inf, length(z)), control = list(trace = 5,fnscale=-1))
N = 7, M = 5 machine precision = 2.22045e-16
L = 0 0 0 0 0 0 0
X0 = 1 1 2 1.5 1 1.5 1
U = inf inf inf inf inf inf inf
At X0, 0 variables are exactly at the bounds
Error in optim(par1, f2, method = "L-BFGS-B", lower = rep(0, length(z)), :
L-BFGS-B needs finite values of 'fn'

最佳答案

在优化的某个时刻,您的函数返回的值大于 .Machine$double.xmax (在我的机器上是 1.797693e+308)。

由于您的功能 f1(...)定义为 sum(log(exp(...))) ,以及自 log(exp(z)) = z对于任何 z,为什么不使用这个:

par1 = c(1, 1, 2, 1.5, 1, 1.5, 1)
x = seq(0, 500, length=100)
f1 = function(par, x){
sum(-(par[7])*(par[1]*x + par[2]*x^2/2 +
par[3] * (par[4]-x)^3/3+par[6] *(x-par[7])^3/3))
}
result <- optim(par1, f1, x=x,
method = "L-BFGS-B",
lower = rep(0, length(par1)), upper = rep(Inf,length(par1)),
control = list(trace = 5,fnscale=-1))

result$par
# [1] 2.026284e-01 2.026284e-01 8.290126e+08 0.000000e+00 1.000000e+00 9.995598e+35 2.920267e+27
result$value
# [1] 2.423136e+147

请注意,参数向量( par )必须是 f1 的第一个参数.

关于r - R 中函数的优化(L-BFGS-B 需要 'fn' 的有限值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23718161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com