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.
Asked
Active
Viewed 4,885 times
11
user7117436
- 298
- 4
- 11
-
I'm curious as to why you need to do this? Are you looking to do something with the weights? – I_Play_With_Data Mar 06 '18 at 13:04
-
@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. – David Arenburg Jan 24 '19 at 09:23
2 Answers
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)
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
dkoehler
- 1