代码是这样的:
lm.loglik3 <-function(y, x, theta){N <-length(y)# theta contains our parameters to be estimated
beta0 <- theta[1]
beta1 <- theta[2]
sigma2 <- theta[3]# x contains our covariates
x1 <- x
logl <--N/2* log(2*pi*sigma2)-1/(2*sigma2)* sum((beta0+beta1*x1-y)^2)
return(-logl)}
# Starting Values
stval <-c(0, 0, 0)
# Optim
res3 <-optim(stval, lm.loglik3, y = df2$v64, x = df2$auth_val, hessian = TRUE)
我正在尝试使用威权主义的程度(给出数值)和收入作为参数来进行最大似然估计。该数据库包含6000个样本。现在的问题是,当我运行代码时,它告诉我“优化时出错:无法在初始参数处评估函数”。有帮助吗?
答案 0 :(得分:0)
您的问题是参数的初始值和对数似然性
logl <--N/2* log(2*pi*sigma2)-1/(2*sigma2)* sum((beta0+beta1*x1-y)^2)
如果sigma2
变为零,则有多种原因:您将日志取零(不好)并除以零(一点也不好)。换句话说,您需要确保sigma2为正。
一种简单的(经典的)精确方法是exp()
输入参数,因此替换
sigma2 <- theta[3]# x contains our covariates
与
sigma2 <- exp(theta[3])# x contains our covariates
这允许optim()
函数使用整个范围的值,但是将实线转换为正线,因此似然性是有意义的。请记住,sigma2
函数返回的optim()
的参数估计值将是记录的值。
使用完整的代码和输出进行更新
完整代码(上面显示了更改)是
lm.loglik3 <-function(y, x, theta){
N <-length(y)# theta contains our parameters to be estimated
beta0 <- theta[1]
beta1 <- theta[2]
sigma2 <- exp(theta[3]) # x contains our covariates
x1 <- x
logl <- -N/2* log(2*pi*sigma2)-1/(2*sigma2)* sum((beta0+beta1*x1-y)^2)
return(-logl)
}
使用初始化时
stval <-c(0, 0, 0)
X <- c(8, 2, 4, 1, 1, 13, 2, 9, 2, 1, 7, 2, 1, 2, 4, 8, 3, 2, 2, 2,
3, 1, 14, 2, 1, 5, 2, 2, 4, 5)
Y <- c(18, 17, 13, 13, 20, 11, 11, 9, 8, 14, 8, 7, 15, 13, 12, 17,
10, 16, 14, 10, 13, 10, 12, 16, 18, 9, 9, 15, 13, 18)
我们得到
> res3
$par
[1] 13.4598331 -0.1292182 2.4549731
$value
[1] 79.3809
$counts
function gradient
178 NA
$convergence
[1] 0
$message
NULL
$hessian
[,1] [,2] [,3]
[1,] 2.57596526 9.8745335 0.00558974
[2,] 9.87453350 67.7478863 0.00621170
[3,] 0.00558974 0.0062117 14.98815391
答案 1 :(得分:0)
lm.loglik2 <- function(y, x, theta){
N <- length(y)
# theta contains our parameters to be estimated
beta0 <- theta[1]
beta1 <- theta[2]
sigma2 <- exp(theta[3])
logl <- - N / 2 * log(2 * pi * sigma2) -
1 / (2 * sigma2) * sum((beta0 + beta1 * x - y)^2)
return(-logl)
}
# Starting Values
stval <- c(0, 0, 1)
>
> # Optim
> res3 <- optim(stval,
lm.loglik2,
x=X
y = Y,
hessian = TRUE)
Error in optim(stval, lm.loglik2, y = Y, x = X, hessian = TRUE) :
the function cannot be evaluated for its initial parameters
sigma2 系数:0.46 标准错误:0.07
X <-df2 $ v64
dput(df2$v64[1:30])
c(8, 2, 4, 1, 1, 13, 2, 9, 2, 1, 7, 2, 1, 2, 4, 8, 3, 2, 2, 2,
3, 1, 14, 2, 1, 5, 2, 2, 4, 5)
Y <-df2 $ auth_val
dput(df2$auth_val[1:30])
c(18, 17, 13, 13, 20, 11, 11, 9, 8, 14, 8, 7, 15, 13, 12, 17,
10, 16, 14, 10, 13, 10, 12, 16, 18, 9, 9, 15, 13, 18)