编织和绘制神经网络

AI5*_*963 6 r knitr

我试图绘制一些神经网络输出,但我没有得到任何结果.绘制正常的东西就像plot(iris)工作正常一样,但是neuralnetwork()对象的某些东西似乎没有以相同的方式绘制.

我的文件看起来像:

---
title: "stack"
author: "stack"
date: "today"
output:
  pdf_document: default
  html_document: default
---


```{r}
library(neuralnet)
AND <- c(rep(0,3),1)
binary.data <- data.frame(expand.grid(c(0,1), c(0,1)), AND)
net <- neuralnet(AND~Var1+Var2,  binary.data, hidden=0,err.fct="ce", linear.output=FALSE)
plot(net)
```
Run Code Online (Sandbox Code Playgroud)

我没有输出.同样的文件绘制其他东西就好了.有什么想法吗?

Yih*_*Xie 9

之前已在rmarkdown存储库中报告并回答了此问题.在这里,我只是想解释为什么它不起作用的技术原因.

从帮助页面?neuralnet::plot.nn:

Usage

    ## S3 method for class 'nn'
    plot(x, rep = NULL, x.entry = NULL, x.out = NULL,
        ....


Arguments

  ...

  rep   repetition of the neural network. If rep="best", the repetition
        with the smallest error will be plotted. If not stated all repetitions
        will be plotted, each in a separate window.
Run Code Online (Sandbox Code Playgroud)

从源代码(v1.33):

> neuralnet:::plot.nn
function (x, rep = NULL, x.entry = NULL, x.out = NULL, radius = 0.15, 
    .... 
{
    ....
    if (is.null(rep)) {
        for (i in 1:length(net$weights)) {
            ....
            grDevices::dev.new()
            plot.nn(net, rep = i, 
                    ....
        }
    }
Run Code Online (Sandbox Code Playgroud)

我已经在....上面省略了irrelvant信息.基本上如果你没有指定rep,neuralnet:::plot.nn将打开新的图形设备来绘制图.这将打破knitr的图形记录,因为

  1. 它打开了图形设备,但没有要求它们打开录音(通过dev.control(displaylist = 'enable'));
  2. knitr默认使用自己的设备来记录图形; 如果用户打开新设备,则无法保证knitr可以保存新的图表.一般来说,我不鼓励在绘制函数时操纵图形设备.

我不是神经网络包的作者,但我建议作者放弃dev.new(),或者至少让它成为有条件的,例如

if (interactive()) grDevices::dev.new()
Run Code Online (Sandbox Code Playgroud)

我猜这个dev.new()电话的意图可能是在新窗口中显示情节,但实际上并不能保证用户可以看到窗口.交互式 R会话的默认图形设备是窗口/屏幕设备(如果可用,例如x11()quartz()),但很可能默认设备已被用户或包作者更改.

我建议条件,interactive()因为对于非交互式R会话,打开新的(默认情况下,屏幕外)设备可能没有多大意义.


nei*_*fws 5

我认为问题在于,对于类的对象nnplot使用参数rep。如果rep未定义,则所有重复都会在单独的窗口中绘制(当在 RMarkdown 之外运行时)。如果rep = "best",则仅生成误差最小的图。所以这应该有效:

```{r}
library(neuralnet)
AND <- c(rep(0,3),1)
binary.data <- data.frame(expand.grid(c(0,1), c(0,1)), AND)
net <- neuralnet(AND~Var1+Var2,  binary.data, hidden=0,err.fct="ce", 
linear.output=FALSE)
plot(net, rep = "best")
```
Run Code Online (Sandbox Code Playgroud)

?plot.nn