You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言nls()设置起始点与上下限时报错的解决问询

解决nls()函数维度不匹配错误的方案

错误原因

你试图通过将mconst的上下限都设为0来固定截距,但nls的"port"算法仍会把这个参数视为待估计项。计算梯度时,固定参数的梯度是标量0,而其他参数的梯度是与数据集长度(100行)一致的向量,两者相乘时出现维度不匹配,引发错误。

解决方法

方法1:直接移除截距项(推荐)

既然要固定截距为0,直接在公式中指定无截距模型,同时移除参数列表中的mconst:

start_vec <- c(x1 = 0, x2 = 0, x3 = 0, x4 = 0, x5 = 0)
upper_vec <- c(x1 = Inf, x2 = Inf, x3 = Inf, x4 = Inf, x5 = Inf)
lower_vec <- c(x1 = -Inf, x2 = -Inf, x3 = -Inf, x4 = -Inf, x5 = -Inf)

nls(formula = y ~ 0 + x1 + x2 + x3 + x4 + x5,
    data = dat, 
    start = start_vec, 
    lower = lower_vec,
    upper = upper_vec,
    algorithm = "port")

方法2:使用offset固定截距

如果需要保留mconst的写法逻辑,可以用offset将截距固定为0,此时不需要在参数列表中包含mconst:

start_vec <- c(x1 = 0, x2 = 0, x3 = 0, x4 = 0, x5 = 0)
upper_vec <- c(x1 = Inf, x2 = Inf, x3 = Inf, x4 = Inf, x5 = Inf)
lower_vec <- c(x1 = -Inf, x2 = -Inf, x3 = -Inf, x4 = -Inf, x5 = -Inf)

nls(formula = y ~ offset(0) + x1 + x2 + x3 + x4 + x5,
    data = dat, 
    start = start_vec, 
    lower = lower_vec,
    upper = upper_vec,
    algorithm = "port")

额外提示

如果你的模型本质是线性的(当前公式为线性形式),使用lm(y ~ 0 + x1 + x2 + x3 + x4 + x5, data = dat)会比nls更高效、稳定,无需设置起始值和算法。

内容的提问来源于stack exchange,提问作者Moritz Schwarz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 21:57:00