问题描述
我注意到我可以使用 nls
拟合参数向量,如下所示。这让我决定要设置的参数数量。如下例所示;我适合的地方 y = k + a_1 x ^ 2 + a_2 x ^ 3 + a_3 x ^ 3
。我可以简单地更改初始值的数量,这会更改要估计的系数的数量。
I noticed that I can fit parameter vector, as below, using nls
. This let's me decide the number of parameters I want to fit. As in the example below; where I am fitting y = k + a_1 x^2 + a_2 x^3 + a_3 x^3
. I can simply change the number of initial values, which change the number of co-efficients to estimate.
但是,这种方法不适用于 nls2
。它只是对待适合 y = k + a_1 * x
的三倍!
But, this approach doesn't work with nls2
. It just treats fits the y = k + a_1 * x
, three times!
我的问题是如何获得 nls2
来确定基于初始值(或类似值)的参数数量,例如 nls
。
My questions is how to get nls2
to determine the number of parameters to fit based on the initial values - or something similar - as in the case with nls
.
我对 nls
或类似软件包没有太多经验。因此,我正在尝试修复。我想 nls2
比 nls
...
I don't have a lot of experience with nls
or similar packages. So, I am trying to mend that. I am guessing nls2
has more capabilities than nls
...
x <- c(32,64,96,118,126,144,152.5,158)
y <- c(99.5,104.8,108.5,100,86,64,35.3,15)
model_fun <- function(x, int_sep, para) {
int_sep + rowSums(sapply(1:length(para), function(i) para[i] * x^i))
}
使用 nls
包
With nls
package
mod_nls <- nls(y ~ model_fun(x, int_sep, para),
start = list(int_sep = 0, para=c(1, 1, 1)))
mod_nls
# Nonlinear regression model
# model: y ~ model_fun(x, int_sep, para)
# data: parent.frame()
# int_sep para1 para2 para3
# 1.269e+02 -1.626e+00 2.910e-02 -1.468e-04
# residual sum-of-squares: 65.87
#
# Number of iterations to convergence: 1
# Achieved convergence tolerance: 1.732e-07
使用 nls2
包
With nls2
package
mod_nls2 <- nls2(y ~ model_fun(x, int_sep, para),
start = list(int_sep = 0, para=c(1, 1, 1)))
mod_nls2
# Nonlinear regression model
# model: y ~ model_fun(x, int_sep, para)
# data: parent.frame()
# int_sep para
# 143.0438 -0.5966
# residual sum-of-squares: 3661
#
# Number of iterations to convergence: 1
# Achieved convergence tolerance: 7.602e-09
(编辑:我对此特定模型不感兴趣-似乎是一个简单的例子)
推荐答案
nls2
将 start =
参数转换为数据内部框架,因此如果您以 as.data.frame(as.list(start))
的形式提供它(在示例中 works表示它创建了具有1行2列的数据帧,两个参数中的每一个都包含一列-请注意dat一个框架列可以容纳复杂的对象),那么您应该可以:
nls2
converts the start=
argument to a data frame internally so if you provide it in a form such that as.data.frame(as.list(start))
works (where in the example "works" means it creates a data frame with 1 row and 2 columns, one column for each of the two parameters -- note that data frame columns can hold complex objects) then you should be OK:
nls2(y ~ model_fun(x, int_sep, para),
start = list(int_sep = 0, para = I(t(c(1, 1, 1)))))
这篇关于与nls不同,nls2将向量化的初始值视为单个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!