Error in readRDS(file.rds) - r

Summary:
I installed the rstan package, now I am facing this error:
Error in readRDS(file.rds) : unknown input format
Description:
> traceback()
5: readRDS(file.rds)
4: is(obj <- readRDS(file.rds), "stanmodel")
3: stan_model(file, model_name = model_name, model_code = model_code,
stanc_ret = NULL, boost_lib = boost_lib, eigen_lib = eigen_lib,
save_dso = save_dso, verbose = verbose)
2: stan(file = fName, data = datalist, init = list(inlist), chains = 1,
iter = n.it, pars = c("f", "tau"), warmup = n.warm, seed = computerID +
1000) at functions.r#131
1: RunModel(11, myT, nu, lambda, rho, BDRi, Pars, computerID, n.it,
n.warm, getwd())
Environment:
RStan Version: 2.16.2
R Version 3.4.1 (2017-06-30)
Operating System: Windows 10

Please test whether this works:
install.packages('rstan')
library(rstan)
saveRDS(mtcars, file = 'test.rds')
readRDS('test.rds')
Works fine for me

My problem is solved. I use writeLines command.
library(rstan)
scode <- "
parameters {
real y[2];
}
model {
y[1] ~ normal(0, 1);
y[2] ~ double_exponential(0, 2);
}
"
writeLines(scode, "mymodel.stan")
mymodel <- stan("mymodel.stan", iter = 10, verbose = FALSE)

Related

Error when trying to apply Lambda and Alpha arguments when using ml_linear_regression in Spark (using R)

I am trying to run a regression with alpha = 1 and lambda = 0, however I keep getting an error.
I will write down the whole code and packages.
library(sparklyr)
library(dplyr, warn.conflicts = FALSE)
library(ggplot2)
library(gridExtra)
# Install the `glmnet` package in your user library
if(system("hostname", intern=TRUE) == "gbef4001.hpc.wvu.edu"){
Sys.setenv(SPARK_HOME = "/opt/cloudera/parcels/CDH/lib/spark/")
sc <- spark_connect(
master = "yarn-client",
source = "/opt/cloudera/parcels/CDH/lib/spark/bin/spark-submit",
version="2.4.0")
} else {
sc <- spark_connect(master = "local")
}
path.data <- paste("file://", getwd(), "/prostate.csv", sep = "")
Then I turn the data into a dataframe in both R and then in Spark
prostate_df <- read.csv(path.data)
prostate_sdf <- sdf_copy_to(sc, prostate_df, "prostate_sdf", overwrite = TRUE)
Then I try to run an regression using the lambda and alpha arguments
prostate_sdf %>% ml_linear_regression(lpsa ~ lcavol + lweight + age + lbph + svi + lcp + gleason + pgg45, alpha=1, lambda=0)
But I keep getting the error below
Error: 2 components of `...` were not used. We detected these problematic arguments: * `alpha` * `lambda` Did you misspecify an argument?
Any idea how to remedy this? thanks

R package gamlss used inside foreach() fails to find an object

I'm trying to get leave-one-out predicted values. Please help me with this "can't find object" issue. I have searched for similar issues, but haven't managed to figure it out. This is on Windows 10.
Thanks in advance
library('gamlss')
library('foreach')
library('doParallel')
registerDoParallel(cores = 4)
# Generate data
set.seed(314)
sample.size <- 30
input.processed.cut <- data.frame(TP = round(runif(sample.size) * 100),
FP = round(runif(sample.size) * 100),
x = runif(sample.size))
# Fit Beta-binomial
model3 <- gamlss(formula = cbind(TP, FP) ~ x,
family = BB,
data = input.processed.cut)
# Get the leave-one-out values
loo_predict.mu <- function(model.obj, input.data) {
yhat <- foreach(i = 1 : nrow(input.data), .packages="gamlss", .combine = rbind) %dopar% {
updated.model.obj <- update(model.obj, data = input.data[-i, ])
predict(updated.model.obj, what = "mu", newdata = input.data[i,], type = "response")
}
return(data.frame(result = yhat[, 1], row.names = NULL))
}
par.run <- loo_predict.mu(model3, input.processed.cut)
# Error in { : task 1 failed - "object 'input.data' not found"
> version
_
platform x86_64-w64-mingw32
arch x86_64
os mingw32
system x86_64, mingw32
status
major 3
minor 4.3
year 2017
month 11
day 30
svn rev 73796
language R
version.string R version 3.4.3 (2017-11-30)
nickname Kite-Eating Tree
I got a response from gamlss team and verified that their solution works. The only thing to change was to provide "data" along with "newdata" to predict().
loo_predict.mu <- function(model.obj, input.data) {
yhat <- foreach(i = 1 : nrow(input.data), .packages="gamlss", .combine = rbind) %dopar% {
updated.model.obj <- update(model.obj, data = input.data[-i, ])
predict(updated.model.obj, what = "mu", data = input.data[-i, ],
newdata = input.data[i,], type = "response")
}
return(data.frame(result = yhat[, 1], row.names = NULL))
}

R version 3.3.2, Windows 10: gstat package: Error in fitting a variogram model using 'fit.variogram' function

I am having some problem with fit.variogram function of the gstat package. My code, data, error message and traceback() message can be found below. Any suggestion to approach this problem would be appreciated.
library(gstat)
mydf<-as.data.frame(read.table("Sample_data.xlsx",header = TRUE,sep =
",",na.strings = "EMPTY"))
coordinates(mydf) = ~x+y
c.vgm.exp<-variogram(z~1,data=mydf,cutoff=60000, width = 60000/15)
c.vgm.fit<-fit.variogram(c.vgm.exp,vgm(nugget=1000000,psill=6000000,model
="Exp",range = 40000),fit.method = 7)
Data file can be obtained from:
https://gtvault-my.sharepoint.com/personal/srathore6_gatech_edu/_layouts/15/guestaccess.aspx?docid=0b5983d45c9544203a5081cd501c64de4&authkey=AYhC8_ZVvGFG18JHHWMgUa4&expiration=2017-12-01T19%3a45%3a23.000Z
Error Message:
c.vgm.fit<-fit.variogram(c.vgm.exp,vgm(nugget=1000000,psill=6000000,model
="Exp",range = 40000),fit.method = 7)
Error in switch(model, exponential = fit.exponential(v.object, c0 = nugget,:
EXPR must be a length 1 vector
traceback()
1: fit.variogram(c.vgm.exp, vgm(nugget = 1e+06, psill = 6e+06, model =
"Exp", range = 40000), fit.method = 7)

Error (Setting objectives in 'params' and 'obj' at the same time is not allowed) in xgboost() function in R

Below is the code which i am executing on XGBOOST,
data(Glass, package = "mlbench")
levels(Glass$Type) <- c(0:5) #Proper Sequence. Should start with 0
Glass$Type <- as.integer(as.character(Glass$Type))
set.seed(100)
options(scipen = 999)
library(caret)
R_index <- createDataPartition(Glass$Type, p=.7, list = FALSE)
gl_train <- Glass[R_index,]
gl_test <- Glass[-R_index,]
'%ni%' <- Negate('%in%')
library(xgboost)
library(Matrix)
#Creating the matrix for training the model
train_gl <- xgb.DMatrix(data.matrix(gl_train[ ,colnames(gl_train) %ni% 'Type']),
label = as.numeric(gl_train$Type))
test_gl <- xgb.DMatrix(data.matrix(gl_test[ ,colnames(gl_test) %ni% 'Type']))
watchlist <- list(train = gl_train, test = gl_test)
#Define the parameters and cross validate
param <- list("objective" = "multi:softmax",
"eval_metric" = "mlogloss",
"num_class" = length(unique(gl_train$Type)))
cv.nround <- 5
cv.nfold <- 3
cvMod <- xgb.cv(param = param, data = train_gl,
nfold = cv.nfold,
nrounds = cv.nround,
watchlist=watchlist)
#Build the Model
nrounds = 50
xgMod = xgboost(param = param, data = train_gl, nrounds = nrounds, watchlist = watchlist)
After executing xgMod i am getting the below mentioned error,
Error in check.custom.obj() :
Setting objectives in 'params' and 'obj' at the same time is not allowed
Let me know what's wrong in my code.
Any help is appreciated.
Regards,
Mohan
The problem is due to the watchlist parameter passed to xgboost.
watchlist is a parameter of xgb.train but not of xgboost, hence it is considered by xgboost like "other parameters" (...) .
The following code
xgMod <- xgboost(param = param, data = train_gl, nrounds = nrounds)
works correctly
[1] train-mlogloss:1.259886
[2] train-mlogloss:0.963367
[3] train-mlogloss:0.755535
[4] train-mlogloss:0.601647
[5] train-mlogloss:0.478923
...

R2WinBUGS - Warning messages

I am trying to use R2WinBUGS using this example:
code
(Please only consider the part: ### 5.4. Analysis using WinBUGS)
I am getting this error message:
Error in file(con, "wb") : cannot open the connection
In addition: Warning messages:
1: In file.create(to[okay]) :
cannot create file 'c:/Program Files/WinBUGS14//System/Rsrc/Registry_Rsave.odc', reason 'Permission denied'
2: In file(con, "wb") :
cannot open file 'c:/Program Files/WinBUGS14//System/Rsrc/Registry.odc': Permission denied
Warning message:
running command '"c:/Program Files/WinBUGS14//WinBUGS14.exe" /par "D:/R2WinBUGS/normal/script.txt"' had status 1
>
I am not sure whether this is crucial for correct functionality (everything else seems to look ok). Is there a way to get rid of this?
Thanks.
Christian
PS:
This is the R code:
library(R2WinBUGS)
setwd("D:/R2WinBUGS/normal")
y10 <- rnorm(n = 10, mean = 600, sd = 30) # Sample of 10 birds
y1000 <- rnorm(n = 1000, mean = 600, sd = 30) # Sample of 1000 birds
# Save BUGS description of the model to working directory
sink("model.txt")
cat("
model {
# Priors
population.mean ~ dunif(0,5000) # Normal parameterized by precision
precision <- 1 / population.variance # Precision = 1/variance
population.variance <- population.sd * population.sd
population.sd ~ dunif(0,100)
# Likelihood
for(i in 1:nobs){
mass[i] ~ dnorm(population.mean, precision)
}
}
",fill=TRUE)
sink()
# Package all the stuff to be handed over to WinBUGS
# Bundle data
win.data <- list(mass = y1000, nobs = length(y1000))
# Function to generate starting values
inits <- function()
list (population.mean = rnorm(1,600), population.sd = runif(1, 1, 30))
# Parameters to be monitored (= to estimate)
params <- c("population.mean", "population.sd", "population.variance")
# MCMC settings
nc <- 3 # Number of chains
ni <- 1000 # Number of draws from posterior (for each chain)
nb <- 1 # Number of draws to discard as burn-in
nt <- 1 # Thinning rate
# Start Gibbs sampler: Run model in WinBUGS and save results in object called out
out <- bugs(data = win.data, inits = inits, parameters.to.save = params, model.file = "model.txt",
n.thin = nt, n.chains = nc, n.burnin = nb, n.iter = ni, debug = TRUE, DIC = TRUE, working.directory = getwd())
ls()
out # Produces a summary of the object
names(out)
str(out)
hist(out$summary[,8]) # Rhat values in the eighth column of the summary
which(out$summary[,8] > 1.1) # None in this case
par(mfrow = c(3,1))
matplot(out$sims.array[1:999,1:3,1], type = "l")
matplot(out$sims.array[,,2] , type = "l")
matplot(out$sims.array[,,3] , type = "l")
par(mfrow = c(3,1))
matplot(out$sims.array[1:20,1:3,1], type = "l")
matplot(out$sims.array[1:20,,2] , type = "l")
matplot(out$sims.array[1:20,,3] , type = "l")
par(mfrow = c(3,1))
hist(out$sims.list$population.mean, col = "grey")
hist(out$sims.list$population.sd, col = "blue")
hist(out$sims.list$population.variance, col = "green")
par(mfrow = c(1,1))
plot(out$sims.list$population.mean, out$sims.list$population.sd)
pairs(cbind(out$sims.list$population.mean, out$sims.list$population.sd, out$sims.list$population.variance))
summary(out$sims.list$population.mean)
summary(out$sims.list$population.sd)
sd(out$sims.list$population.mean)
sd(out$sims.list$population.sd)
summary(lm(y1000 ~ 1))
Probably it is windows UAC fault. By default UAC doesn't allow programms to write in almost anything except the user's folder. You can change that by running R as administrator. But I think that will change the library folder unless it is hardcoded in Renviron.site (inside R\etc folder), but I'm not 100% sure about that.
I was able to fix the problem by defining "bugs.directory".
out <- bugs(data = win.data, inits = inits, parameters.to.save = params, model.file = "model.txt", n.thin = nt, n.chains = nc, n.burnin = nb, n.iter = ni, debug = FALSE, DIC = TRUE, working.directory = getwd(), bugs.directory = 'c:/WinBUGS14')
Your link goes out to a huge file that spans many chapters of a book. In the comments section it says:
# You may have to add a 'working.directory' argument to calls to
# the function bugs().
Have you done that yet? There's also a bunch of user-specific stuff like:
setwd("C:/_Marc Kery/_WinBUGS book/Naked code") # May have to adapt that
Have you appropriately modified those items?

Resources