【发布时间】:2021-10-07 18:52:22
【问题描述】:
我是使用遗传算法,尤其是遗传算法的初学者。 我想知道如何优化具有两个自变量和多个参数的函数。 我的第一个变量是连续变量,第二个变量是二进制变量。 这是我生成的代码,但它不起作用。
Var1_obs <- c(-1.942000, -1.338000, -2.065000, -2.080125, -3.247944, -5.365086,
-1.608000, -3.970000, -1.423000, -8.180000, -4.620000, -1.657000,
-5.200000, -6.850000, -6.950000, -1.180000, -1.175000, -1.969000,
-1.115000, -2.620000, -1.870000, -0.433000, -1.102000, -2.093687,
-2.480000, -0.580000, -0.600000, -1.807383, -2.367000, -2.276017,
-2.125331)
Var2_obs <- c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1)
TE_obs <- c(92.73958, 93.39356, 84.39019, 93.40717, 97.53228, 92.04734, 82.06016,
78.50015, 83.43671, 55.24498, 67.92513, 77.53455, 65.33344, 47.05005,
46.52794, 96.79697, 84.79326, 83.64457, 82.17259, 88.96605, 84.93663,
83.16691, 95.22838, 96.46441, 79.61302, 80.39901, 88.38439, 72.23954,
85.64084, 69.33542, 82.30360)
data<-data.frame(Var1_obs,Var2_obs,TE_obs)
plot(data$Var1_obs[data$Var2_obs==0],data$TE_obs[data$Var2_obs==0],
xlim=range(data$Var1_obs), ylim=range(data$TE_obs), col=2, pch=19,
xlab='Var1_obs', ylab='TE_obs')
points(data$Var1_obs[data$Var2_obs==1],data$TE_obs[data$Var2_obs==1],
xlim=range(data$Var1_obs), ylim=range(data$TE_obs), col=3, pch=19)
library(GA)
library(hydroGOF)
My_function <- function(Var1, Var2, P1, P2, P3, P4, P5, P6, P7) {
A <- (-1 * (Var1 + P1 - P2) - sqrt((Var1 + P1 - P2)^2 + 4 * (Var1 * P2))) / (2 * P2)
B <- 1 - P1 / Var1
C <- c(A, B)
Sel <- c(A > B, B > A)
RS <- C[Sel]
PC <- 100 / (1 + exp(P3 / 25 * (Var1 - P4)))
RMC <- (1 - RS)
symp <- RMC * (1 / (P5 / 1000) - 1) * 100 * (1 - P6)
apo <- (1 - PC / 100) * (1 / (P5 / 1000) - 1) * 100 * (P6)
TE_Pred <- (apo + symp) * (1 + P7 * Var2)
NRMSE <- (nrmse(TE_Pred, TE_obs, na.rm = T, norm = "sd"))
# if(is.na(NRMSE)|is.nan(NRMSE)|is.infinite(NRMSE)) NRMSE <- -1e6
return(NRMSE)
}
# ----------------------- BOUNDARIES --------------------------- #
P1 <- c(-3.5, -2.3)
P2 <- c(5, 15)
P3 <- c(15, 60)
P4 <- c(-7.5, -6)
P5 <- c(500, 600)
P6 <- c(0.3, 0.6)
P7 <- c(-1, 0)
min_boundary <- c(P1[1], P2[1], P3[1], P4[1], P5[1], P6[1], P7[1])
max_boundary <- c(P1[2], P2[2], P3[2], P4[2], P5[2], P6[2], P7[2])
ga(
type = "real-valued",
fitness = function(x) -My_function(Var1 = Var1_obs, Var2 = Var2_obs, P1[1],
P2[2], P3[3], P4[4], P5[5], P6[6], P7[7]),
lower = min_boundary, upper = max_boundary,
popSize = 50, maxiter = 1000, run = 100
)
我在运行代码时得到了这个
#> GA | iter = 1 | Mean = NaN | Best = -Inf
#> GA | iter = 2 | Mean = NaN | Best = -Inf
#> Error in if (object@run >= run) break :
#> missing value where TRUE/FALSE needed
感谢您的帮助
【问题讨论】:
-
只是为了我的理解,你想优化
My_Function函数在哪些变量上? Var1 和 Var2?对吗? -
或者换句话说:您想找到 My_Function 的值最佳的 Var1 和 Var2 的值吗?还是要优化 P1-P7 参数?
-
@David 感谢您的提问。我想将“我的函数”拟合到数据(TE_obs ~ Var1-obs),如图所示:i.stack.imgur.com/CmqPj.jpg 我用这个命令绘制了图表:data
-
重申一下,在给定
Var1和Var2的输入的情况下,您希望最小化TE_obs的值,对吗? -
@David 是的,没错
标签: r optimization mathematical-optimization genetic-algorithm