Generate graph structure of a multi-layer perceptron
generatePerceptron <- function(numLayers, layerWidth){
# Generates a graphNel structure representing a multi-layer perceptron
# Starts and ends with single nodes "R" and "T", with multiple "layers" in between.
# numLayers is the number of Layers, layerWidth is the number of nodes in the layer
require(graph)
layerNames <- LETTERS[1:numLayers]
layer <- layerNames[1]
layerList <- lapply(layerNames, function(layer) {
paste(rep(layer, each = 2), 1:layerWidth, sep = "")
})
edgeMat <- NULL
for(i in 2:length(layerList)){
for(j in 1:length(layerList[[i]])){
for(k in 1:length(layerList[[i - 1]])){
edgeMat <- rbind(edgeMat, c(layerList[[i -1 ]][j], layerList[[i]][k]))
}
}
}
edgeMat <- rbind(t(sapply(layerList[[1]], function(nd) c("R", nd))), edgeMat)
edgeMat <- rbind(edgeMat, t(sapply(layerList[[numLayers]], function(nd) c(nd, "T"))))
dimnames(edgeMat) <- NULL
ftM2graphNEL(edgeMat)
}
g <- generatePerceptron(3, 2)
plot(g)