Ggplot2 stat_function shows an invalid function

I want to build a loglijelihood of a series of independent distributed random variables Bernoulli y with parameter p, which is a function (logistic function) of some function x. This logistic function also has parameter b. This is the parameter that I want to evaluate. So I want to build a log-likelihood as a function of b. I want to do this in R using ggplot2 because I want to get better at them.

My creation of the loglajelihood function can and should be done better, but that is not my point here. The problem is that the constructed logarithmic constant is constant on the interval (-5.5). This seems wrong. Especially because when I call a function with some arbitrary b in this interval, it returns a different value. Why is this happening? Thank.

library(ggplot2)
set.seed(123)

# parameters 
n=100
mu=0
s=2
b<-0.2

# functions 
logit <- function(x,b){1/(1+exp(-b*x))}

# simulation of data
x<-rnorm(n,mu,s)
y_prob<-logit(x,b)
y<-rbinom(n,1,y_prob)
df<-data.frame(x,y)

# loglikelihood function 
loglikelihood<-function(b,df){
  prd<-1
  for (i in 1:NROW(df)){
    events<-logit(df$x[i],b)
    nonevents<-1-events
    prd<-prd*events^df$y[i]*nonevents^(1-df$y[i])
  }
  return(sum(log(prd)))
}


loglikelihood(0.3,df)

p2<-ggplot(data=data.frame(b=c(-5,5)), aes(b)) + stat_function(fun=loglikelihood, args=list(df=df))
p2<-p2+xlab("b") + ylab("loglikelihood")
p2
+4
source share
1 answer

. "" stat_function. R , . , sin(1:10) 1 10. , ,

loglikelihood(seq(-5,5, by=.1), df)
# [1] -20534.44

"" R-, . - Vectorize. ,

vloglikelihood <- Vectorize(loglikelihood, vectorize.args="b")
vloglikelihood(seq(-5,5, by=.1), df)
# [1] -463.67919 -454.67142 -445.66980 -436.67470 -427.68654 -418.70574 ...

vloglikelihood R. ,

ggplot(data=data.frame(b=c(-5,5)), aes(b)) + 
    stat_function(fun=vloglikelihood, args=list(df=df)) +
    xlab("b") + ylab("loglikelihood")

enter image description here

+3

Source: https://habr.com/ru/post/1546075/


All Articles