if (FALSE) {
# Construct a neural Bayes estimator for replicated univariate Gaussian
# data with unknown mean and standard deviation.
# Load R and Julia packages
library("NeuralEstimators")
library("JuliaConnectoR")
juliaEval("using NeuralEstimators, Flux, Distributions")
# Define the neural-network architecture
estimator <- juliaEval('
d = 1 # dimension of each replicate
p = 2 # number of parameters in the model
w = 32 # width of each layer
psi = Chain(Dense(d, w, relu), Dense(w, w, relu))
phi = Chain(Dense(w, w, relu), Dense(w, p))
deepset = DeepSet(psi, phi)
estimator = PointEstimator(deepset)
')
# Sampler from the prior
sampler <- function(K) {
mu <- rnorm(K) # Gaussian prior for the mean
sigma <- rgamma(K, 1) # Gamma prior for the standard deviation
theta <- matrix(c(mu, sigma), byrow = TRUE, ncol = K)
return(theta)
}
# Data simulator
simulator <- function(theta_set, m) {
apply(theta_set, 2, function(theta) {
t(rnorm(m, theta[1], theta[2]))
}, simplify = FALSE)
}
# Train using fixed parameter and data sets
theta_train <- sampler(10000)
theta_val <- sampler(2000)
m <- 30 # number of iid replicates
Z_train <- simulator(theta_train, m)
Z_val <- simulator(theta_val, m)
estimator <- train(estimator,
theta_train = theta_train,
theta_val = theta_val,
Z_train = Z_train,
Z_val = Z_val)
# Train using simulation on-the-fly (requires Julia package RCall)
estimator <- train(estimator, sampler = sampler, simulator = simulator, m = m)
##### Simulation on-the-fly using Julia functions ####
# Defining the sampler and simulator in Julia can improve computational
# efficiency by avoiding the overhead of communicating between R and Julia.
# Julia is also fast (comparable to C) and so it can be useful to define
# these functions in Julia when they involve for-loops.
# Parameter sampler
sampler <- juliaEval("
function sampler(K)
mu = rand(Normal(0, 1), K)
sigma = rand(Gamma(1), K)
theta = hcat(mu, sigma)'
return theta
end")
# Data simulator
simulator <- juliaEval("
function simulator(theta_matrix, m)
Z = [rand(Normal(theta[1], theta[2]), 1, m) for theta in eachcol(theta_matrix)]
return Z
end")
# Train the estimator
estimator <- train(estimator, sampler = sampler, simulator = simulator, m = m)}
Run the code above in your browser using DataLab