【问题标题】:How to get activation values from Tensor for Keras model?如何从 Tensor for Keras 模型中获取激活值?
【发布时间】:2019-10-12 03:12:20
【问题描述】:

我正在尝试从层中的节点访问激活值。

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)

【问题讨论】:

  • 那么,您的意见是什么?
  • 你必须向我们展示你所尝试的一切,如果你犯了错误我们不会知道。

标签: tensorflow keras tensorflow2.0


【解决方案1】:

尝试使用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])

【讨论】:

  • 这个函数可以喂(10,4)个数据。
  • @HashRocketSyntax 你必须举个例子说明问题,你说的没有意义,批处理维度不应该改变。
  • 这很尴尬,我在预测 test_x 的同时看着 train_x 的形状,想知道为什么我的值比预期的要多。
猜你喜欢
  • 2020-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-22
  • 1970-01-01
相关资源
最近更新 更多