Inst/doc/deriv play code.R

require(madness)
set.seed(1234)
x <- matrix(rnorm(16), ncol = 1)
madx <- madness(x, vtag = "y", xtag = "x")
# the show method could use some work
print(madx)

x <- seq(1, 10, 1)
y <- x^2

madx <- madness(rnorm(1), vtag = "y", xtag = "x")

y <- rexp(1000, 1/1e5)

madx2 <- 
  
library(dfdr)  
f <- function(x) x^2 + sin(x)


df <- d(f, "x")
df

p <- function(theta) dexp_man(10000, 1/theta)
dp <- d( f = p, x = "theta")

p <- function(theta) {sum(log(dexp(y, 1/theta)))}

dexp_man  <- function(x, rate) {
  exp(-x * rate) * rate
}

loglik_exp <- function(x, rate) {
    sum(log(dexp_man(x, rate)))
}

dmix_exp  <- function(x, ws, rates) {
  wn <- exp(ws) / sum(exp(ws))
  z <- mapply(dexp_man, rate = rates, 
              MoreArgs = list(x = x), SIMPLIFY = F)
  as.vector( wn %*% matrix(unlist(z), ncol = length(x), byrow = T))
}

dmix_exp2  <- function(x, ws, rates) {
  wn <- exp(ws) / sum(exp(ws))
  ct <- 0
  for (i in (1:length(wn))) {
    ct <- ct + wn[i] * dexp_man(x, rates[i])
  }
  ct
}

library(base)
library(Deriv)
library(numDeriv)

l_lnorm  <- function(y, mu, sigma) {
  -log(sigma)*length(y) + sum(-(log(y) - mu)^2) / (2 * sigma^2)
}

l_lnorm2 <- function(y, pars) {
  -log(pars[2])*length(y) + sum(-(log(y) - pars[1])^2) / (2 * pars[2]^2)
}

g_l_lnorm <- Deriv(l_lnorm, x = c('mu', 'sigma'))

g_l_lnorm2 <- function(pars, y) grad(l_lnorm2, x = pars, y = y)

f <- function(x, y) x + y; deriv(~f(x, x^2), "x")

f <- function(x) x^2
Deriv(f)
Atan1988/FlexFit documentation built on Jan. 16, 2022, 12:32 a.m.