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")
# Define the neural-network architecture
estimator <- juliaEval('
n = 1 # dimension of each replicate
d = 2 # number of parameters in the model
w = 32 # width of each hidden layer
psi = Chain(Dense(n, w, relu), Dense(w, w, relu))
phi = Chain(Dense(w, w, relu), Dense(w, d))
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)
##### Simulation on-the-fly using R functions ####
juliaEval("using RCall") # requires the 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.
juliaEval("using Distributions")
# 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
estimator <- train(estimator, sampler = sampler, simulator = simulator, m = m)}
Run the code above in your browser using DataLab