0

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)
Kermit
  • 4,922
  • 4
  • 42
  • 74

1 Answers1

1

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])
Kermit
  • 4,922
  • 4
  • 42
  • 74
zihaozhihao
  • 4,197
  • 2
  • 15
  • 25
  • You can feed (10,4) data input this function. – zihaozhihao Oct 12 '19 at 03:30
  • @HashRocketSyntax You have to make an example that shows the problem, what you said makes no sense, the batch dimension should not change. – Dr. Snoopy Oct 19 '19 at 13:23
  • Well this is embarrassing, I was looking at the shape of `train_x` while predicting on `test_x` and wondering why I had way more values than anticipated. – Kermit Oct 19 '19 at 13:46