print("The values for my anova function and the lm() are the same")
[1] "The values for my anova function and the lm() are the same"
4.1
n =30; set.seed(0);X =runif(n)*4-2;Y =1+3*X +rnorm(n);fit1 =lm(Y ~ X); summary(fit1) # beta0_hat = 1.0161; beta1_hat = 2.9304, o
Call:
lm(formula = Y ~ X)
Residuals:
Min 1Q Median 3Q Max
-1.2486 -0.5518 -0.1069 0.5028 1.6770
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 1.0161 0.1480 6.867 1.84e-07 ***
X 2.9304 0.1241 23.605 < 2e-16 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 0.8068 on 28 degrees of freedom
Multiple R-squared: 0.9522, Adjusted R-squared: 0.9504
F-statistic: 557.2 on 1 and 28 DF, p-value: < 2.2e-16
myFullObj <-function(b,sig) { Xmat <-cbind(1, X) e <- Y -drop(Xmat %*% b) n <-length(Y) loglik <- n *0.5*log(2* pi * sig^2) +sum(e^2) / (2* sig^2)return(loglik)}
4.2
sig <-2myObj1 <-function(b) myFullObj(b, sig)B_BFGS <-optim(par=c(0,0), fn=myObj1, method="BFGS")B_BFGS$par
print("My coefficients are the same as those produced by the lm() function up to the 5th decimal place.")
[1] "My coefficients are the same as those produced by the lm() function up to the 5th decimal place."
4.3
myObj2 <-function(params) { b <- params[1:2] sig <- params[3]myFullObj(b, sig)}B_LBFGSB <-optim(par=c(0,0,1), fn=myObj2,method="L-BFGS-B",lower=c(-Inf,-Inf,1e-5))B_LBFGSB$par
[1] 1.0160618 2.9303970 0.7794035
fit1$coefficients
(Intercept) X
1.016062 2.930397
print("My coefficients are the same as those produced by the lm() function up to the 6th decimal place.")
[1] "My coefficients are the same as those produced by the lm() function up to the 6th decimal place."
Would you expect the MLE for sig to be equal to the estimate produced by lm (“Residualstandard error”)?
I would expect that the maximum likelihood estimation for sigma would be similiar, but smaller than the one used by the lm (ordinary least squares). This is because ordinary least squares takes into account the number of parameters in the model into its variance estimate, but MLE does not.