nls:在确定的迭代次数中循环和中断

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nls:在确定的迭代次数中循环和中断相关的知识,希望对你有一定的参考价值。

我喜欢两个顺序操作:

1)在子集中调整两个nls模型; 2)循环模型只需要迭代次数= 1。

我做的第一步:

#Packages
library(minpack.lm)

# Data set - Diameter in function of Feature and Age
Feature<-sort(rep(c("A","B"),22))
Age<-c(60,72,88,96,27,
36,48,60,72,88,96,27,36,48,60,72,
88,96,27,36,48,60,27,27,36,48,60,
72,88,96,27,36,48,60,72,88,96,27,
36,48,60,72,88,96)
Diameter<-c(13.9,16.2,
19.1,19.3,4.7,6.7,9.6,11.2,13.1,15.3,
15.4,5.4,7,9.9,11.7,13.4,16.1,16.2,
5.9,8.3,12.3,14.5,2.3,5.2,6.2,8.6,9.3,
11.3,15.1,15.5,5,7,7.9,8.4,10.5,14,14,
4.1,4.9,6,6.7,7.7,8,8.2)
d<-dados <- data.frame(Feature,Age,Diameter)
str(d)

#Create a nls model (Levenberg-Marquardt  algoritm) for each Feature (A abd B)
e1<- Diameter ~ a1 * Age^a2 
Fecture_vec<-unique(d$Feature)
mod_ND <- list() #List for save each model
for(i in 1:length(Fecture_vec))
     d2 <- subset(d, d$Feature == Fecture_vec[i])
     mod_ND[[i]] <-  nlsLM(e1, data = d2,
     start = list(a1 = 0.1, a2 = 10),
     control = nls.control(maxiter = 1000))
print(summary(mod_ND[[i]]))

#

到目前为止,这么好,但如果我尝试使用999模拟进行循环并使用coef(mod_ND[[i]])[1]coef(mod_ND[[i]])[2]回收起始值,并在迭代次数为1时停止:

e1<- Diameter ~ a1 * Age^a2 
Fecture_vec<-unique(d$Feature)
mod_ND <- list() #List for save each model
for(i in 1:length(Fecture_vec))
     d2 <- subset(d, d$Feature == Fecture_vec[i])
     mod_ND[[i]] <-  nlsLM(e1, data = d2,
     start = list(a1 = 0.1, a2 = 10),
     control = nls.control(maxiter = 1000))
Xs<-data.frame()
for(z in 1:999)
     d2 <- subset(d, d$Feature == Fecture_vec[i])
     mod_ND[[z]] <-  nlsLM(e1, data = d2,
     start = list(a1 = coef(mod_ND[[i]])[1], a2 = mod_ND[[i]])[2]),
     control = nls.control(maxiter = 1000))
   if (mod_ND[[z,c(finIter")]] <= 1) break  ## Stop when iteractions =1
print(summary(mod_ND[[z]]))


#

不行!!请问有什么想法?

答案
#Packages
library(minpack.lm)
library(dplyr)

m<-function(d, a=0.01,b=10)

   mod<- nlsLM(Diameter ~ a1 * Age^a2,start = list(a1 = a, a2 = b),control = nls.control(maxiter = 1000), data = d)
   par1<- summary(mod)$coefficients[[1]]
    par2 <- summary(mod)$coefficients[[2]]
   print(summary(mod))

   if(mod$convInfo[["finIter"]]>1)    
       m(d,par1,par2)      
  else
       print(" --------Feature B-----------")
            
    
list_models <- dlply(d,.(Feature),m)   
list_models

以上是关于nls:在确定的迭代次数中循环和中断的主要内容,如果未能解决你的问题,请参考以下文章

NLS 函数 - 迭代次数超过最大值

`nls` 拟合错误:无论起始值,总是达到最大迭代次数

如何在刀片foreach循环中获取迭代次数

Python中的循环结构

Django模板:获取嵌套循环的总迭代次数

根据 for 循环中的迭代次数向列表添加不同的值