11

I am using package Keras in R to do a neural network. How may I extract the output from a hidden layer? I found an example in python, but it is just I have no idea how to do that in R.

user7117436
  • 298
  • 4
  • 11

2 Answers2

8

You can get the answer here.

Here it is:

model <- ...  # create the original model
layer_name <- 'my_layer'
intermediate_layer_model <- keras_model(inputs = model$input,
                                    outputs = get_layer(model, layer_name)$output)
intermediate_output <- predict(intermediate_layer_model, data)
Zephyr
  • 997
  • 4
  • 10
  • 20
Perochkin
  • 311
  • 2
  • 6
0

I cannot comment as this account is new, so I'll post this as an additional answer:
When using get_layer() using index = ... instead of layer_name = ..., it should be noted that there is a discrepancy between using it as written by Perochkin and using it in the python-style of model$get_layer(...):

model$get_layer(index = as.integer(5))

returns the layer on the zero-based layer index, while

get_layer(model, index = as.integer(5))

or

model %>% get_layer(index = as.integer(5))

is 1-based, so these return different layers. I didn't find this information anywhere else, so I wanted to share, as this cost me quite some time to find out