如何从张量获得Kera模型的活化值? [英] How to get activation values from Tensor for Keras model?
本文介绍了如何从张量获得Kera模型的活化值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从层中的节点访问激活值。
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'>
我尝试了eval()
和K.function
的几种不同方法,但都没有成功。我也尝试了这篇文章中的每种方法Keras, How to get the output of each layer?
如何使用此对象?
型号 只是使用大家都熟悉的东西。
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)
推荐答案
尝试使用K.function
并向该函数提供一批train_x
。
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])
这篇关于如何从张量获得Kera模型的活化值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文