将损失函数应用于连续函数

时间:2018-10-03 22:28:43

标签: r bayesian

我有一个连续的后验概率函数,需要花费多长时间才能上班:

#components of prior distrobution
busRideTime = function(x)
    {dnorm(x,10,2)}
busWaitTime = function(x)
    {dunif(x,0,10)}
walkingTime = function(x)
    {dnorm(x,4,2.5)}

#using Fourier transformation to combine components of prior (multiplying fourier transformations and then doing the inverse is equivalent to take the convolution of the functions)
priortimeToBPS = function(t)     
{   
    as.numeric(
        fft(
            fft(busRideTime(t))*
            fft(busWaitTime(t))*
            fft(walkingTime(t))
        ,inverse=TRUE)
    )
 }

# new data
X <- {c(24, 21, 31, 23, 17, 16, 18, 18, 17)}

# normal distribution of new data
N <- length(X)
MU <- mean(X)
SIGMA <- sd(X)

likelihood = function(s) 
    {dnorm(s, mean=MU, sd=SIGMA^2)}

#non-normalized posterior
falseposteriortimetoBPS = function(e)
    {
        (likelihood(e)*priortimeToBPS(e))
    }

#computing normalization constant
V = integrate(falseposteriortimetoBPS,0,Inf)

#normalized posterior
posteriortimetoBPS = function(r)
    {
        (likelihood(r)*priortimeToBPS(r))/(as.numeric(V[1]))
    }
plot(posteriortimetoBPS(1:40),xlab="Time to get to BPS  (min)",ylab="density",type='l')

我有一个损失函数,该函数可将数据转换为估算我上晚/上班时损失的函数(以模拟数据为例):

Posterior = rnorm(1000,20,7)

lossFunction <- function(a, predictions) {
    mean(
        sapply(predictions,
            function (theta) {
                ifelse((a-theta)>0,(a-theta),
                ifelse((a-theta)>-2,(a-theta)-2,-(a-theta)-2)
                )
            }       
        )
    )
}
losses <- sapply(c(0:40), function (tm) { lossFunction(tm, Posterior);})
plot(losses,xlab="leaving x minutes before the start of work",ylab="loss",type='l')

如何结合这两件事?我曾尝试模拟后验函数以生成数据,但我真的不知道该怎么做,并且网上没有太多有关模拟函数的信息(有关模拟“模型”的很多知识,但我不知道该如何改变模型)也可以用于模型。谢谢!

0 个答案:

没有答案