Applying Cost Functions in R

China☆狼群 提交于 2019-12-01 09:43:21

We could use optim for optimization or use glm directly

set.seed(1)
X <- matrix(rnorm(1000), ncol=10) # some random data
Y <- sample(0:1, 100, replace=TRUE)

# Implement Sigmoid function
sigmoid <- function(z) {
  g <- 1/(1+exp(-z))
  return(g)
}

cost.glm <- function(theta,X) {
  m <- nrow(X)
  g <- sigmoid(X%*%theta)
  (1/m)*sum((-Y*log(g)) - ((1-Y)*log(1-g)))
}

X1 <- cbind(1, X)
optim(par=rep(0,ncol(X1)), fn = cost.glm, method='CG',
      X=X1, control=list(trace=TRUE))
#$par 
#[1] -0.067896075 -0.102393236 -0.295101743  0.616223350  0.124031764  0.126735986 -0.029509039 -0.008790282  0.211808300 -0.038330703 -0.210447146
#$value
#[1] 0.6255513
#$counts
#function gradient 
#      53       28 

glm(Y~X, family=binomial)$coefficients
# (Intercept)           X1           X2           X3           X4           X5           X6           X7           X8           X9          X10 
#-0.067890451 -0.102411613 -0.295104858  0.616228141  0.124017980  0.126737807 -0.029523206 -0.008790988  0.211810613 -0.038319484 -0.210445717 

The figure below shows how the cost and the coefficients iteratively computed with optim converge to the ones computed with glm.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!