Guest User

Untitled

a guest
May 27th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. library(keras)
  2. library(mrsdeploy)
  3.  
  4. #Keras objects cannot be saved and restored across R sessions, so load a keras model and convert it to a r model
  5. kerasModel = load_model_hdf5('my_model.h5')
  6. rModel = serialize_model(kerasModel, include_optimizer = TRUE)
  7.  
  8. kerasFunc <- function(x) {
  9. library(keras)
  10. kerasModel = unserialize_model(rModel, custom_objects = NULL, compile = TRUE)
  11. prediction <- predict_classes(kerasModel, x)
  12. answer = as.list(prediction)
  13. }
  14.  
  15. serviceName <- paste0("kerasService", round(as.numeric(Sys.time()), 0))
  16. api <- publishService(
  17. serviceName,
  18. code = kerasFunc,
  19. model = rModel,
  20. inputs = list(x="matrix"),
  21. outputs = list(answer="vector"),
  22. v = "v1.0.0"
  23. )
  24.  
  25. swagger <- api$swagger()
  26. cat(swagger, file = "swagger.json", append = FALSE)
  27.  
  28. # Load test data
  29. mnist <- dataset_mnist()
  30. x_test <- mnist$test$x
  31. x_test <- array_reshape(x_test, c(nrow(x_test), 784))
  32. x_test <- x_test / 255
  33. x = matrix(c(x_test[1,]), nrow=1, ncol=784)
  34.  
  35. #consume the keras model api
  36. result<-api$kerasFunc(x)
  37. #output is the predicted number
  38. print(result$output("answer"))
Add Comment
Please, Sign In to add comment