我如何在R中使用季节性虚拟对象运行指数nls?

cunj1qz1  于 2023-05-04  发布在  其他
关注(0)|答案(3)|浏览(118)

我在用R中的季节性假人运行nls回归时遇到了麻烦。没有季节性的假人我也能做到,但没有。这是我目前掌握的情况:

year=floor(time(lsts))
> month=round(time(lsts)-year,4)
> month.f=factor(month)
> dummies=model.matrix(~month.f)
hotdogNLS<-nls(lsts~beta1/(1+exp(beta2+beta3*t)),start=list(beta1=2500,beta2=0.5,beta3=-0.5),trace=F)

摘要(hotdogNLS)

Formula: lsts ~ beta1/(1 + exp(beta2 + beta3 * t))

Parameters:
        Estimate Std. Error t value Pr(>|t|)    
beta1  2.030e+03  5.874e+01   34.55   <2e-16 ***
beta2  1.146e+00  5.267e-02   21.76   <2e-16 ***
beta3 -1.116e-02  7.668e-04  -14.56   <2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 192.3 on 333 degrees of freedom

Number of iterations to convergence: 8 
Achieved convergence tolerance: 2.054e-06

我如何包括季节性假人?谢谢!

67up9zun

67up9zun1#

我不认为nls的虚拟实现与glm中的虚拟实现一样,因为nls的“公式”是一个真实的的数学公式,与glm不同。
但是,您可以指定是否必须为每个虚拟类单独评估参数:

data(cars)
    # define the dummy
    cars$dummy <- as.factor(LETTERS[1:5])
    # code as 0/1 the dummy with a column per dummy level
    cars$A<- as.numeric(cars$dummy=="A")
    cars$B<- as.numeric(cars$dummy=="B")
    cars$C<- as.numeric(cars$dummy=="C")
    cars$D<- as.numeric(cars$dummy=="D")
    cars$E<- as.numeric(cars$dummy=="E")

    # precise in the formula where the dummy level should play out
    # here in the intercept:
    model <- nls(dist~beta1*speed^beta2+beta3*A+beta4*B+beta5*C+beta6*D+beta7*E,data=cars)

    model

    Nonlinear regression model
      model: dist ~ beta1 * speed^beta2 + beta3 * A + beta4 * B + beta5 * C + beta6 * D + beta7 * E
      data: cars
      beta1   beta2   beta3   beta4   beta5   beta6   beta7 
      0.2069  1.8580  2.8266  5.3973 13.0002  9.3539  2.5361 
      residual sum-of-squares: 10040

      Number of iterations to convergence: 8 
      Achieved convergence tolerance: 4.924e-06
q7solyqu

q7solyqu2#

您可以使用factor来子集估计系数,如alpha[dummy]

data(cars)
cars$dummy <- as.factor(LETTERS[1:5])

nls(dist ~ alpha[dummy] + beta1*speed^beta2, data=cars, start=list(beta1=.2, beta2=3, alpha=rep(10, nlevels(cars$dummy))))
#Nonlinear regression model
#  model: dist ~ alpha[dummy] + beta1 * speed^beta2
#   data: cars
#  beta1   beta2  alpha1  alpha2  alpha3  alpha4  alpha5 
# 0.2069  1.8580  2.8264  5.3971 13.0000  9.3537  2.5359 
# residual sum-of-squares: 10040
#
#Number of iterations to convergence: 12 
#Achieved convergence tolerance: 2.372e-06
fhity93d

fhity93d3#

@cmbarbu的手工设置dummies的答案应该可以工作,但这可以通过nlme::gnls()params参数更容易地完成:

nls(lsts ~ beta1/(1+exp(beta2+beta3*t)),
    start = list(beta1=2500,beta2=0.5,beta3=-0.5),
    params = beta1 + beta2 + beta3 ~ season
)

(see ?nlme::gnls了解详细信息,如何为不同的非线性参数指定不同的线性子模型等。)

相关问题