'R: Obtaining a Vector of Neural Network Weights

I am working with the R programming language.

Using the following link (https://www.r-bloggers.com/2015/09/fitting-a-neural-network-in-r-neuralnet-package/), I was able to plot a simple Neural Network:

> library(neuralnet)
> 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,]
> 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,]
> 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)

enter image description here

I was able to extract all the weights from this Neural Network using the following line of code:

 nn$weights
[[1]]
[[1]][[1]]
               [,1]        [,2]         [,3]        [,4]        [,5]
 [1,] -1.2203079850 -1.76938328    0.3902553   0.9255087  0.04967656
 [2,]  2.5558666743 29.15547389   -4.6616911 -48.1251159 10.95073281
 [3,]  0.0000061424  1.17886373 -109.7263646  -3.2249960  0.68070610
 [4,]  1.2631590702  0.02429057    0.3996311  -1.8534716 -0.12248632
 [5,] -0.3859840038  0.91387767   -1.7377923  -0.1336971  0.07863433
 [6,] -0.6579390110  0.42564432  -16.2547002  -1.0202761 -0.43242987
 [7,]  5.5067332472  2.80523053    1.7124912  -0.2846291 -1.44356850
 [8,] -0.2744910691  0.02451080    2.9130914  -0.6850058  1.33970879
 [9,]  0.0737063948 -1.50770678  -34.9650266  -4.8888364 -1.29302559
[10,] -2.7050887015  3.53838932    2.8720359   2.6717384 -0.69399384
[11,] -1.4024666457  1.20623841    3.0431943  -7.2887193  0.40211354
[12,] -1.4818934686  1.20431620   -1.7348877  -2.0280757  0.76471423
[13,] -1.3117853448 -1.45204009    0.2898592  -0.3257896 -1.63673510
[14,] -6.3987992324  5.13814123   -5.0388277   0.9623181  2.56448828

[[1]][[2]]
           [,1]        [,2]       [,3]
[1,]  0.5152474   1.4617391  0.2842433
[2,]  1.5105105  -2.1325773  1.7741087
[3,]  1.4690984  -0.6267573  1.0241078
[4,] -0.9517777 -15.8780821  4.0706049
[5,]  9.6148242  -1.8920040  6.8301080
[6,] -2.2814756   0.1298490 -0.7070506

[[1]][[3]]
           [,1]
[1,]  0.0523065
[2,]  0.7023349
[3,] -0.9850700
[4,]  0.6879870

My Question: Is it possible to reformat this list so that the weights are clearly defined by "layer"? E.g. Layer 1 - list all weights. Layer 2 - list all weights, etc.

Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source