How to export a trained Neural Network in R to a function in JavaScript or PHP or other language?

I'm doing the following basic R tutorial below for Machine Learning:

https://datascienceplus.com/fitting-neural-network-in-r/

As suggested there, I just ran the following commands:

set.seed(500)
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,]
lm.fit <- glm(medv~., data=train)
summary(lm.fit)
pr.lm <- predict(lm.fit,test)
MSE.lm <- sum((pr.lm - test$medv)^2)/nrow(test)
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,]
library(neuralnet)
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)

At that point I have a trained Neural Network.

Then, if I want to visualize the Neural Network I can do:

plot(nn)

Then I get the following (click the image to enlarge it):

enter image description here

Just with that information from the image, you can manually create a function (straight forward) in whatever language, for example: Javascript, so you can pass the values for the inputs and then you get the value for the output.

My question is: Due to that's a simple process, is there any R package that you can pass the nn variable as we did with: plot(nn) above so you get something like:

> generateCode(nn, 'javascript')
function (crim, zn, indus, chas, nox, rm, age, dis, rad, tax, ptratio, black, lstat) {
  var medv;
  ...
  ...
  ...
  medv = ...;
  return medv;
}

I think this is a very common use case because that will let us to use already trained NN directly on our application without having a running instance of R listenting for requests from our app which can be done, by the way, by the R package plumber which exposes our existing R code through web APIs.

Even though you can do that process manually you will need to do than in an authomatic way because in a real scenario you will be actively training/discarding tons of Neural Networks.

Thanks!

h2o package allows you to convert the models you have built to either a Plain Old Java Object (POJO) or a Model ObJect, Optimized (MOJO).

H2O-generated MOJO and POJO models are intended to be easily embeddable in any Java environment.

1 Like

Thank you @andresrcs, that helped me!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.