Home > OS >  Matrix multiplication neural network style
Matrix multiplication neural network style

Time:08-18

Think of a neural network. Layer 1 has n1 nodes. The data for them is stored in the columns of a data.frame or a matrix. In this example, it has 5 nodes (4 regular ones plus a column of ones for the "bias"):

l1 = head(iris[,1:4], 7)
l1$one = 1

Layer 2 has n2 nodes. For calculating each Layer 2 node, I have a vector of weights. The length of each vector is n1. For example, with n2 = 2, the weights are

wts = list()
wts[[1]] = 1:5
wts[[2]] = -3:1

I need to calculate the values of the nodes in Layer 2. In other words,

  • for each node of Layer 2 (i in 1:n2)
  • for each row of the Layer 1 data
  • multiply each element in that row of l1 by the corresponding element in wts[[i]] and add up the products

What is an easy way to do this? I am mostly looking for efficiency or speed. I hope there are already functions to do this.

CodePudding user response:

This is just a single matrix-matrix multiplication:

as.matrix(l1) %*% do.call(cbind, wts)

It would be much easier if you store everything as matrices. Don't use data frames or lists here.

  • Related