Unknown variable error in JAGS model - r

I'm currently trying to develop a model in JAGS, but I unfortunately keep getting the following error:
Error in jags.model(file = "Model.txt", n.adapt = MCMCAdapt) :
RUNTIME ERROR:
Compilation error on line 15.
Unknown variable precedentCount
Either supply values for this variable with the data
or define it on the left hand side of a relation.
The following is what is in the file titled, "Model.txt":
model {
for (i in 1:citationCount) {
Z[i] ~ dbern(Z.hat[i])
Z.hat[i] <- phi(kappa - lambda*pow(x.precedent[newPrecedentID[i]] - x.brief[newBriefID[i]], 2))
}
for (j in 1:briefCount) {
x.brief[newBriefID[j]] ~ dnorm(0,1)
}
for (k in 1:precedentCount) {
x.precedent[newPrecedentID[k]] ~ dnorm(0,1)
}
kappa ~ dunif(-10,10)
lambda ~ dunif(-10, 0)
}
I'm a little confused as to why the error is occurring, as precedentCount is already defined in R's environment:
> precedentCount
[1] 650
The same thing is true for briefCount and citationCount, yet these have not yielded the same error (yet, at least):
> briefCount
[1] 126
> citationCount
[1] 2948
If anyone can advise how I can address this problem, I would greatly appreciate it.

You need to give JAGS all data as the argument jags.model(data = list(...)). precedentCount came up because it was just the first error.
data_list <- list(precedentCount = 650,
briefCount = 126,
citationCount = 2948,
newPrecedentID = ...))
jags.model(file = "Model.txt", n.adapt = MCMCAdapt, data = data_list)

Related

Error in eval(expr, p): object 'X' not found; predict (BayesARIMAX)

I am trying to use BayesARIMAX to model and predict us gdp (you can find the data here: https://fred.stlouisfed.org/series/GDP).I followed the example (https://cran.r-project.org/web/packages/BayesARIMAX/BayesARIMAX.pdf) to build my model. I didnt have any major issue to build the model(used error handling to overcome Getting chol.default error when using BayesARIMAX in R issue). However could not get the prediction of the model. I tried to look for solution and there is no example of predicting the model that is build using BayesARIMAX. Every time that I run the "predict" I get the following error:
"Error in eval(expr, p) : object 'X' not found"
Here is my code.
library(xts)
library(zoo)
library(tseries)
library(tidyverse)
library(fpp2)
gdp <- read.csv("GDP.csv", head = T)
date.q <- as.Date(gdp[, 1], "%Y-%m-%d")
gdp <- xts(gdp[,2],date.q)
train.row <- 248
number.row <- dim(merge.data)[1]
gdp.train <- gdp[1:train.row]
gdp.test <- gdp[(train.row+1):number.row]
date.test <- date.q[(train.row+1):number.row]
library(BayesARIMAX)
#wrote this function to handle randomly procuded error due to MCMC simulation
test_function <- function(a,b,P=1,Q=1,D=1,error_count = 0)
{
tryCatch(
{
model = BayesARIMAX(Y=a,X = b,p=P,q=Q,d=D)
return(model)
},
error = function(cond)
{
error_count=error_count+1
if (error_count <40)
{
test_function(a,b,P,Q,D,error_count = error_count)
}
else
{
print(paste("Model doesnt converge for ARIMA(",P,D,Q,")"))
print(cond)
}
}
)
}
set.seed(1)
x = rnorm(length(gdp.train),4,1)
bayes_arima_model <- test_function(a = gdp.train,b=x,P = 3,D = 2,Q = 2)
bayes_arima_pred <- xts(predict(bayes_arima_model[[1]],newxreg = x[1:3])$pred,date.test)
and here is the error code
Error in eval(expr, p) : object 'X' not found
Here is how I resolve the issue after reading through the BayesARIMAX code (https://rdrr.io/cran/BayesARIMAX/src/R/BayesianARIMAX.R) . I basically created the variable "X" and passed it to predict function to get the result. You just have to set the length of X variable equal to number of prediction.
here is the solution code for prediction.
X <- c(1:3)
bayes_arima_pred <- xts(predict(bayes_arima_model[[1]],newxreg = X[1:3])$pred,date.test)
which gave me the following results.
bayes_arima_pred
[,1]
2009-01-01 14462.24
2009-04-01 14459.73
2009-07-01 14457.23

R Model returning the error: Too many open devices

I've been working on the creation of a training model in R for MS Azure. When I initially set up the model it all worked fine. Now it's continuously returning the below:
{"error":{"code":"LibraryExecutionError","message":"Module execution encountered an internal library error.","details":[{"code":"FailedToEvaluateRScript","target":"Score Model (RPackage)","message":"The following error occurred during evaluation of R script: R_tryEval: return error: Error in png(file = \"3e25ea05d5bc49d683f4471ff40780bcrViz%03d.png\", bg = \"transparent\") : \n too many open devices\n"}]}}
I haven't changed anything, and have looked around online only to find references to other issues. My code is as follows:
Trainer R Script
# Modify Datatype, factor Level, Replace NA to 0
x <- dataset
for (i in seq_along(x)) {
if (class(x[[i]]) == "character") {
#Convert Type
x[[i]] <- type.convert(x[[i]])
#Apply Levels
# levels(x[[i]]) <- levels(cols_modeled[, names(x)[i]]) # linked with levels in model
}
if (is.numeric(x[[i]]) && is.na(x[[i]]) ){
#print("*** Updating NA to 0")
x[[i]] <- 0
}
}
df1 <- x
rm(x)
set.seed(1234)
model <- svm(Paid ~ ., data= df1, type= "C")
Scorer R Script
library(e1071)
scores <- data.frame( predicted_result = predict(model, dataset))
Has anyone come across this before?

Keras, LIME: No data provided for "lstm__input" in "explain" function

I receive ValueError: No data provided for "lstm__input". Need data for each key in: ['lstm__input'] while executing lime::explain
I have latest lime version and looked thourgh all related topics to my problem. I have LSTM regression network and I don't have any issues training it and predicting values.
As well I don't have any problems predicting values using lime:
class(model)
%keras.engine.sequential.Sequential
model_type.keras.engine.sequential.Sequential <- function(x, ...) {
"regression"}
predict_model.keras.engine.sequential.Sequential <- function (x, newdata, type, ...) {
pred <- predict(object = x, x = newdata)
data.frame (pred) }
predict_model(x = model, newdata = (testX_Matrix), type = 'raw')
explainer <- lime::lime (
x = trainX,
model = model,
bin_continuous = FALSE)
Up to this point everything works fine. When I try to run next lines:
explanation <- lime::explain (
testX,
explainer = explainer,
n_features = 4)
I receive an error:
Error in py_call_impl(callable, dots$args, dots$keywords) :
ValueError: No data provided for "lstm_8_input". Need data for each key in: ['lstm_8_input']
Detailed traceback:
File "C:\Soft\anaconda\envs\R-TENS~1\lib\site-packages\keras\engine\training.py", line 1147, in predict
x, _, _ = self._standardize_user_data(x)
File "C:\Soft\anaconda\envs\R-TENS~1\lib\site-packages\keras\engine\training.py", line 749, in _standardize_user_data
exception_prefix='input')
File "C:\Soft\anaconda\envs\R-TENS~1\lib\site-packages\keras\engine\training_utils.py", line 77, in standardize_input_data
'for each key in: ' + str(names))
I guess main problem comes from the fact that my NN requires only 3-dim matrix (the same I used in predict_model), but lime doesn't work't with objects of class 'array', 'double', 'numeric' so I can't use it.
Has anyone faced such issue? How can I fix it?

replacement has length zero in list() in r

I'm trying to run this code, and I'm using mhadaptive package, but the problem is that when I run these code without writing metropolis_hastings (that is one part of mhadaptive package) error does not occur, but when I add mhadaptive package the error occur. What should I do?
li_F1<-function(pars,data) #defining first function
{
a01<-pars[1] #defining parameters
a11<-pars[2]
epsilon<<-pars[3]
b11<-pars[4]
a02<-pars[5]
a12<-pars[6]
b12<-pars[7]
h<-pars[8]
h[[i]]<-list() #I want my output is be listed in the h
h[[1]]<-0.32082184 #My first value of h is known and other values should calculate by formula
for(i in 2:nrow(F_2_))
{
h[[i]]<- ((a01+a11*(h[[i-1]])*(epsilon^2)*(h[[i-1]])*b11)+(F1[,2])*((a02+a12*(h[[i-1]])*(epsilon^2)+(h[[i-1]])*b12)))
pred<- h[[i]]
}
log_likelihood<-sum(dnorm(prod(h[i]),pred,sd = 1 ,log = TRUE))
return(h[i])
prior<- prior_reg(pars)
return(log_likelihood + prior)
options(digits = 22)
}
prior_reg<-function(pars) #defining another function
{
epsilon<<-pars[3] #error
prior_epsilon<-pt(0.95,5,lower.tail = TRUE,log.p = FALSE)
return(prior_epsilon)
}
F1<-as.matrix(F_2_) #defining my importing data and simulatunig data with them
x<-F1[,1]
y<-F1[,2]
d<-cbind(x,y)
#using mhadaptive package
mcmc_r<-Metro_Hastings(li_func = li_F1,pars=c(10,15,10,10,10,15),par_names=c('a01','a02','a11','a12','b11','b12'),data=d)
By running this code this error occur.
Error in h[[i]] <- list() : replacement has length zero
I'll so much appreciate who help me.

Error in parsing data on R-Studio while running ADF

I cannot seem to get past or understand what is wrong with this error while trying to run the ADF (Augmented Dickey Fuller) test on R-Studio. Will appreciate comments.
library(AER)
library("dynlm", lib.loc="~/R/win-library/3.2")
x<-read.table("C://R Files/protein.csv", header=T, sep=",")
"adf" <- function(x,k = 0, int = TRUE, trend = FALSE){
require(dynlm)
dx <- diff(x)
formula <- paste("dx ~ L(x)")
if(k > 0)
formula <- paste(formula," L(dx,1:k)")
if(trend){
s <- time(x)
t <- ts(s - s[1],start = s[1],freq = frequency(x))
formula <- paste(formula," t")
}
if(!int) formula <- paste(formula," - 1")
summary(dynlm(as.formula(formula)))
}
a<-ts(x$a)
adf(a, k=1, int=T, trend=T)
The error message that I get after this is :
Error in parse(text = x, keep.source = FALSE) :
:1:13: unexpected symbol
1: dx ~ L(x) L
^
It might be this:
formula <- paste(formula," L(dx,1:k)")
You can't just add something to a model. Try doing:
formula <- paste(formula,"+ L(dx,1:k)")
and see if that helps. If not you might want to share the contents of protein.csv so I can try to reproduce your problem.

Resources