11
$\begingroup$

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.

$\endgroup$
2
  • $\begingroup$ I'm curious as to why you need to do this? Are you looking to do something with the weights? $\endgroup$ Mar 6, 2018 at 13:04
  • $\begingroup$ @I_Play_With_Data This is particularly useful when you train an auto-encoder and you want to extract the last layer of the encoder for dimensionality reduction. $\endgroup$ Jan 24, 2019 at 9:23

2 Answers 2

8
$\begingroup$

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)
$\endgroup$
0
$\begingroup$

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.