R - Exporting Neural Network logic as a function from R to JavaScript or PHP


#1

By using R and the following code:

printf <- function(...)print(sprintf(...))

data <- read.csv("https://www.dropbox.com/s/ig4szbkp43kpin1/binary.csv?dl=1", header = TRUE)

data$gre <- (data$gre - min(data$gre)) / (max(data$gre) - min(data$gre))
data$gpa <- (data$gpa - min(data$gpa)) / (max(data$gpa) - min(data$gpa))
data$rank <- (data$rank - min(data$rank)) / (max(data$rank) - min(data$rank))

# Data Partition
set.seed(222)
ind <- sample(2, nrow(data), replace = TRUE, prob = c(0.7, 0.3))
training <- data[ind==1,]
testing <- data[ind==2,]

# Neural Network training
library(neuralnet)
set.seed(333)
n <- neuralnet(admit~gre+gpa+rank,
               data = training,
               hidden = 1,
               err.fct = "ce",
               linear.output = FALSE)
plot(n)

params = training[1, -1]

# Prediction 1:
output_A <- compute(n, params)$net.result[1]

# Prediction 2:
in4 <- 0.0455 + (0.82344*params[1]) + (1.35186*params[2]) + (-0.87435*params[3])
out4 <- 1/(1+exp(-in4))
in5 <- -7.06125 +(8.5741*out4)
out5 <- 1/(1+exp(-in5))
output_B = out5[1,1]

printf('Value A: %.5f', output_A)
printf('Value B: %.5f', output_B)

I created this Neural Network:

enter image description here

which is equivalent to the fragment of code (again pasted below):

# Prediction 2:
in4 <- 0.0455 + (0.82344*params[1]) + (1.35186*params[2]) + (-0.87435*params[3])
out4 <- 1/(1+exp(-in4))
in5 <- -7.06125 +(8.5741*out4)
out5 <- 1/(1+exp(-in5))
output_B = out5[1,1]

My question: is there some way to export the code just above automatically as a sort of function without having to write it manually? My goal is to use it on PHP, JavaScript, etc.

Thanks!