knitr and plotting neural networks

前端 未结 2 1918
暖寄归人
暖寄归人 2021-01-12 20:05

I\'m trying to plot some neural network outputs, but I\'m not getting any result. Plotting normal stuff like plot(iris) works fine, but there\'s something about

2条回答
  •  误落风尘
    2021-01-12 20:16

    This issue has been reported and answered before in the rmarkdown repository. Here I'm only trying to explain the technical reason why it didn't work.

    From the help page ?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.
    

    From the source code (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, 
                        ....
            }
        }
    

    I have omitted the irrelvant information using .... above. Basically if you do not specify rep, neuralnet:::plot.nn will open new graphics devices to draw plots. That will break knitr's graphics recording, because

    1. It opened graphical devices but didn't request them to turn on recording (via dev.control(displaylist = 'enable'));
    2. knitr uses its own device to record graphics by default; if users opened new devices, there is no guarantee that new plots can be saved by knitr. In general, I'd discourage manipulating graphical devices in plotting functions.

    I'm not an author of the neuralnet package, but I'd suggest the authors drop dev.new(), or at least make it conditional, e.g.

    if (interactive()) grDevices::dev.new()
    

    I guess the intention of the dev.new() call was probably to show plots in new windows, but there is really no guarantee that users can see windows. The default graphical device of an interactive R session is a window/screen device (if available, e.g. x11() or quartz()), but it is quite possible that the default device has been changed by users or package authors.

    I suggest the condition interactive() because for a non-interactive R session, it probably does not make much sense to open new (by default, off-screen) devices.

提交回复
热议问题