Is there a way to get the values of a Keras Tensor as a numpy array?
A normal K.eval()
does not work and results in:
AttributeError: 'KerasTensor' object has no attribute 'numpy'
I use the eager execution.
I need this to access and check the outputs of some layers of my sequential model. Example: (out2 = K.eval(cnn.layers[2].output)
)
Minimal example:
import numpy
import tensorflow.keras.models as models
import tensorflow.keras.layers as layers
from keras import backend as K
cnn = models.Sequential([
layers.Conv2D(filters=64, kernel_size=3, activation='relu',
kernel_initializer='he_uniform', padding='same',
input_shape=(32,32,3))],
name='cnn')
res = cnn(numpy.random.random((1,32,32,3)))
print(K.eval(cnn.layers[0].output))
1 Like
I don’t think that is the correct way to do this. You will need to pass your tensors to specific layers to get their individual outputs. Something like this will work:
import numpy
import tensorflow.keras.models as models
import tensorflow.keras.layers as layers
cnn = models.Sequential([layers.Conv2D(64, 3, 1, 'same', input_shape=(32,32,3), name='cnn1')])
# Get the convolutional layer
layer1 = cnn.layers[0]
# Call the layer by passing your tensor to the layer
layer1(numpy.random.random((1,32,32,3)))
1 Like
@darshan_deshpande
i am trying to get the activation maps of conv1, convert it to numpy array to do some computations and then convert them back to kerasTensor and feed them to conv2
using below example, could you please help me
inputs = Input(shape=(48,48,3))
conv1 = Conv2D(32, (3, 3), activation='relu', padding='same')(inputs)
conv1 = Conv2D(32, (3, 3), activation='relu', padding='same')(conv1)
#### here i need to get the activation maps of conv1 ####
pool1 = MaxPooling2D((2, 2))(conv1)
#shape=(None, 64, 24, 24)
conv2 = Conv2D(64, (3, 3), activation='relu', padding='same')(pool1)
conv2 = Conv2D(64, (3, 3), activation='relu', padding='same')(conv2)
pool2 = MaxPooling2D((2, 2))(conv2)
please help…