How to get activation values from Tensor for Keras model?

旧时模样 提交于 2020-01-06 06:57:22

问题


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)

回答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])


来源:https://stackoverflow.com/questions/58350527/how-to-get-activation-values-from-tensor-for-keras-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!