Plot neural net work

2019-03-02 09:18发布

问题:

I use RStudio. In order to plot neural network, I use the package neuralnet and function 'plot' to do the picture. But I find that every time, it will just show me a separated picture by Quartz rather than as in the plot field of RStudio.

Furthermore, plot does not work under RMarkdown.

Can anyone tell how to fix it? It seems I need to disable the Quartz from RStudio. Thanks

The following is the code

    set.seed(500)
    library(MASS)
    data <- Boston
    apply(data,2,function(x) sum(is.na(x)))
    index <- sample(1:nrow(data),round(0.75*nrow(data)))
    train <- data[index,]
    test <- data[-index,]
    lm.fit <- glm(medv~., data=train)
    summary(lm.fit)
    pr.lm <- predict(lm.fit,test)
    MSE.lm <- sum((pr.lm - test$medv)^2)/nrow(test)
    maxs <- apply(data, 2, max) 
    mins <- apply(data, 2, min)
    scaled <- as.data.frame(scale(data, center = mins, scale = maxs-mins))
   train_ <- scaled[index,]
   test_ <- scaled[-index,]
   library(neuralnet)
   n <- names(train_)
   f <- as.formula(paste("medv ~", paste(n[!n %in% "medv"], collapse = " + ")))
   nn <- neuralnet(f,data=train_,hidden=c(5,3),linear.output=T)
   plot(nn)

回答1:

I find it in some place, we can call dev.off() until RStudio never use other device but only studio plot itself

For studio part we can use plot(nn, rep="best") to get the plot. I have not idea why it works.



回答2:

I am late to the post, was having the same issue but by passing "dev="pdf" in chunk options I was able to solve. Hope this proves helpful for anyone else having the same problem. The code

{r,echo=FALSE,dev="pdf"}