Ric*_*col 3 performance loops r lm
我想估计非线性模型的参数。
模型方程为 Z = A * exp(- a * X) + B * exp(- b * Y) + C
我所做的是通过在进行线性回归之前进行指数变换将模型转化为线性问题:
a与b0和1之间,我计算exp_x = exp(- a * X)和exp_y = exp(- b * Y)Z ~ exp_x + exp_y正如我们在这个模拟中看到的那样,它工作得很好
x = 1:10
y = 1:10
combination = expand.grid(x = x, y = y)
df = data.frame(
X = combination$x,
Y = combination$y,
Z = 2 * exp(-0.3 * combination$x) +
5 * exp(-0.6 * combination$y) +
rnorm(n = 100, mean = 0, sd = 0.1 )
)
a_hat = 0
b_hat = 0
best_ols = NULL
best_rsquared = 0
for (a in seq(0.01, 1, 0.01)){
for (b in seq(0.01, 1, 0.01)){
df$exp_x = exp(- a * df$X)
df$exp_y = exp(- b *df$Y)
ols = lm(data = df, formula = Z ~ exp_x + exp_y)
r_squared = summary(ols)$r.squared
if (r_squared > best_rsquared){
best_rsquared = r_squared
a_hat = a
b_hat = b
best_ols = ols
}
}
}
a_hat
b_hat
best_ols
best_rsquared
> a_hat
[1] 0.34
> b_hat
[1] 0.63
> best_ols
Call:
lm(formula = Z ~ exp_x + exp_y, data = df)
Coefficients:
(Intercept) exp_x exp_y
0.0686 2.0550 5.1189
> best_rsquared
[1] 0.9898669
Run Code Online (Sandbox Code Playgroud)
问题:这很慢
大约需要 10 秒,我需要在其他数据帧上执行数千次。
我怎样才能大大加快速度?
也许nls改用。因为你没有set.seed(),看不到我们的预测是否有异曲同工之处,但至少我得到了a和b估计“右”的编辑后:
nmod <- nls( Z ~ A*exp(-a*X)+B*exp(-b*Y), data=df, start=list(A=0.5, B=0.5, a=.1,b=.1))
> coef(nmod)
A B a b
2.0005670 4.9541553 0.2951589 0.5937909
#--------
> nmod
Nonlinear regression model
model: Z ~ A * exp(-a * X) + B * exp(-b * Y)
data: df
A B a b
2.0006 4.9542 0.2952 0.5938
residual sum-of-squares: 0.9114
Number of iterations to convergence: 9
Achieved convergence tolerance: 5.394e-06
Run Code Online (Sandbox Code Playgroud)
比您的 10 秒体验快得多。这是在一台有 8 年历史的机器上。
> system.time( nmod <- nls( Z ~ A*exp(-a*X)+B*exp(-b*Y), data=df, start=list(A=0.5, B=0.5, a=.1,b=.1)) )
user system elapsed
0.036 0.002 0.033
Run Code Online (Sandbox Code Playgroud)