4.2

par(mfrow = c(1,1))

似然函数

lognormlike = function(mu,sigma,data)
{
  out = sum(dnorm(x = data, mean = mu, sd = sigma,log = TRUE))
  return(out)
}

设定数据

纵坐标:似然函数值 横坐标:序列

x = c(25734,22375,21476,16042,15454,15360,15033,14427,10549,10544,
      10501,10491,10147,10118,10016,9240,8862,8121,8030,7986,7927,7903,7712,7691,7021,
      6848,6775,6558,6236,6186,5681)### 数据

sigma = 5000 ### 自定义的sigma
mus = seq(1,20000,100) ### mus就是个序列!是取值的方式
### mus步长100,步长越大精度越差
data = x

初始化ls:

ls = lognormlike(mu = mus, sigma = 100,data = data)
ls = rep(NA,length = mus)
## Warning in rep(NA, length = mus): 只用'length.out'参数里的第一个元素
for(i in 1:length(mus)){
  ls[i] = lognormlike(mu = mus[i],sigma = 100,data = data)
}# 对所有的mu都求出似然值

寻找最大值的位置

plot(mus,ls)
# cbind(mus,ls)
which.max(ls)
## [1] 110
mus[which.max(ls)]
## [1] 10901
abline(v=mus[which.max(ls)],lwd=1,col="steelblue")

#添加一条垂直直线,线宽为1,颜色蓝色
## 更换mu和sigma
## 循环不同的mu与sigma,寻找更好的均值

利用循环寻找需要的似然值 注意对mus的理解

sigma = 5000 ### 自定义的sigma
mus = seq(1,20000,100) ### mus就是个序列!是取值的方式
### mus步长100,步长越大精度越差
data = x
ls = lognormlike(mu = mus, sigma = 100,data = data)
ls = rep(NA,length = mus)
## Warning in rep(NA, length = mus): 只用'length.out'参数里的第一个元素
for(i in 1:length(mus)){
  ls[i] = lognormlike(mu = mus[i],sigma = 100,data = data)
}# 对所有的mu都求出似然值

完成函数

mus = seq(1,20000,100)
sigma = seq(4900,5100)
data = x
ls = matrix(NA, length(mus), length(sigma))
findmax = function(mus,sigma){
for(j in 1:length(sigma)){
  for(i in 1:length(mus))
  {
  ls[i,j] = lognormlike(mu = mus[i],sigma = sigma[j],data = data)
  out = ls
  which.max(ls[i,])
  }
}
  out = which(out==out[which.max(out)],arr.ind=T)
  return(out)
}
findmax(mus,sigma)
##      row col
## [1,] 110  88

老师的细节


# teacher's method
mu = 260:300
sigma = 180:220
ls = matrix(NA, length(mu), length(sigma))
for(i in 1:length(mu))
{
  for(i in 1: length(sigma))
  {
    
  }
}

作业

在固定mu和sigma的同时,找到最大的点,而不是寻找全部的点