r - GRG 非线性 R
问题描述
我想将我的 excel 求解器模型转换为 R 中的模型。我需要找到 3 组坐标,以最小化与其他 5 个给定坐标的距离。我编写了一个程序来计算距离矩阵,该矩阵输出从每个输入到给定坐标的最小距离。我想通过改变输入来最小化这个功能。Id est,我想找到使最小距离之和最小化的坐标。我尝试了几种方法,请参阅下面的代码(是的,我的距离矩阵函数可能有点笨拙,但这是因为我必须将输入减少到 1 个变量才能运行一些算法,例如 nloprt(否则会收到警告). 我也看过一些其他的问题(比如GRG Non-Linear Least Squares (Optimization)) 但他们没有改变/改进解决方案。
# First half of p describes x coordinates, second half the y coordinates # yes thats cluncky
p<-c(2,4,6,5,3,2) # initial points
x_given <- c(2,2.5,4,4,5)
y_given <- c(9,5,7,1,2)
f <- function(Coordinates){
# Predining
Term_1 <- NULL
Term_2 <- NULL
x <- NULL
Distance <- NULL
min_prob <- NULL
l <- length(Coordinates)
l2 <- length(x_given)
half_length <- l/2
s <- l2*half_length
Distance_Matrix <- matrix(c(rep(1,s)), nrow=half_length)
# Creating the distance matrix
for (k in 1:half_length){
for (i in 1:l2){
Term_1[i] <- (Coordinates[k]-x_given[i])^2
Term_2[i] <- (Coordinates[k+half_length]-y_given[i])^2
Distance[i] <- sqrt(Term_1[i]+Term_2[i])
Distance_Matrix[k,i] <- Distance[i]
}
}
d <- Distance_Matrix
# Find the minimum in each row, thats what we want to obtain ánd minimize
for (l in 1:nrow(d)){
min_prob[l] <- min(d[l,])
}
som<-sum(min_prob)
return(som)
}
# Minimise
sol<-optim(p,f)
x<-sol$par[1:3]
y<-sol$par[4:6]
plot(x_given,y_given)
points(x,y,pch=19)
然而,该解决方案显然不是最优的。我尝试使用 nloptr 函数,但不确定要使用哪种算法。我可以使用哪种算法,或者我可以使用/编程解决这个问题的另一个函数?提前致谢(对于详细的长问题,我们深表歉意)
解决方案
看看输出optim
。它达到了迭代极限,还没有收敛。
> optim(p, f)
$`par`
[1] 2.501441 5.002441 5.003209 5.001237 1.995857 2.000265
$value
[1] 0.009927249
$counts
function gradient
501 NA
$convergence
[1] 1
$message
NULL
虽然结果并没有那么不同,但您需要增加迭代次数才能获得收敛。如果这仍然不可接受,请尝试不同的起始值。
> optim(p, f, control = list(maxit = 1000))
$`par`
[1] 2.502806 4.999866 5.000000 5.003009 1.999112 2.000000
$value
[1] 0.005012449
$counts
function gradient
755 NA
$convergence
[1] 0
$message
NULL
推荐阅读
- jquery - 连续计数器中的数字格式问题
- python - 用python在opencv中显示图像
- python-3.x - 使用 Keras 实现置换不变神经网络
- angular - 使用 ViewChild() 从父组件调用子组件的方法
- mysql - Mysql命令行不接受正确的密码
- redis - 我想使用 redis 作为 lru 缓存,我可以按 db 执行还是需要新的 redis 实例?
- odoo - 限制odoo中网页的编辑权限
- c++ - 链表中的分段错误
- catboost - skopt 的 BayesSearchCV 与 CatBoost
- c# - 捆绑包在我的 ASP.NET 网站中不起作用