Kermit
Kermit

Reputation: 5982

How to get activation values from Tensor for Keras model?

I am trying to access the activation values from my nodes in a layer.

l0_out = model.layers[0].output

print(l0_out)
print(type(l0_out))
Tensor("fc1_1/Relu:0", shape=(None, 10), dtype=float32)

<class 'tensorflow.python.framework.ops.Tensor'>

I've tried several different ways of eval() and K.function without success. I've also tried every method in this post Keras, How to get the output of each layer?

How can I work with this object?


MODEL Just using something everyone is familiar with.

import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import Adam

iris_data = load_iris()

x = iris_data.data
y_ = iris_data.target.reshape(-1, 1)

encoder = OneHotEncoder(sparse=False)
y = encoder.fit_transform(y_)

train_x, test_x, train_y, test_y = train_test_split(x, y, test_size=0.20)


model = Sequential()
model.add(Dense(10, input_shape=(4,), activation='relu', name='fc1'))
model.add(Dense(10, activation='relu', name='fc2'))
model.add(Dense(3, activation='softmax', name='output'))

model.compile(optimizer=Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])

print(model.summary())

# Train
model.fit(train_x, train_y, verbose=2, batch_size=5, epochs=200)

Upvotes: 0

Views: 1614

Answers (1)

zihaozhihao
zihaozhihao

Reputation: 4475

Try to use K.function and feed one batch of train_x into the function.

from keras import backend as K

get_relu_output = K.function([model.layers[0].input], [model.layers[0].output])
relu_output = get_relu_output([train_x])

Upvotes: 1

Related Questions