如何从 Tensor 获取 Keras 模型的激活值?
How to get activation values from Tensor for Keras model?
我正在尝试从层中的节点访问激活值。
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
的几种不同方式,但都没有成功。 post
中的所有方法我都试过了
如何使用此对象?
型号
就用大家都熟悉的东西吧。
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])
我正在尝试从层中的节点访问激活值。
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
的几种不同方式,但都没有成功。 post
如何使用此对象?
型号 就用大家都熟悉的东西吧。
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])