调用nls()报‘step factor低于minFactor’错误,但geom_smooth()可拟合曲线
解决nls拟合逻辑曲线的"step factor reduced below 'minFactor'"错误
核心问题:你在直接调用
nls()时写反了公式的自变量和因变量
ggplot的geom_smooth里用的是y ~ Asym/(1+exp((xmid-x)/scal)),对应wei(体重)是因变量y,age(年龄)是自变量x,符合数据趋势(年龄越大体重越趋近饱和);但你写的nls()公式是age ~ Asym/(1+exp((xmid-wei)/scal)),强行把age当因变量、wei当自变量,完全违背数据规律,导致迭代无法收敛。修正后的代码:
library(ggplot2) library(data.table) fil_dat <- as.data.table(list( wei = c(3.1000, 5.9500, 6.3800, 11.4540, 15.6413, 16.9321, 19.3580, 18.8071, 20.0017, 20.5871, 20.9078, 21.6712), age = c(7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84) )) # 保留正确的ggplot拟合代码 ggplot(data = fil_dat , aes(x = age , y = wei)) + geom_point() + geom_smooth(aes(group = NULL), method = "nls", se = F, formula = y ~ Asym/(1+exp((xmid-x)/scal)), method.args = list(start = list(Asym = 30 , xmid = 5 , scal = 5))) # 修正nls公式,与ggplot保持一致,同时优化初始值(可选,但更稳定) model <- nls(formula = wei ~ Asym/(1+exp((xmid-age)/scal)), data = fil_dat, start = list(Asym = 22, xmid = 30, scal = 10)) # 查看拟合参数 summary(model)
- 补充说明:
如果你确实需要用wei预测age,不能用逻辑斯蒂模型——你的数据中age随wei是单调递增且无明显饱和趋势的,逻辑斯蒂的S型曲线完全不匹配这种关系,建议换用线性模型或对数模型。但从你的ggplot代码来看,需求是拟合体重随年龄的生长曲线,修正公式即可解决收敛问题。
内容的提问来源于stack exchange,提问作者BartekT
相关产品推荐
相关产品推荐

