Python 如何从每层Keras获取数组中的输出值
我是python和Keras的初学者。我将Keras与tensorflow后端一起使用。我想从Keras中的每个层(隐藏层和输出层)获取数组中的值。我怎么做 这是我的顺序模型Python 如何从每层Keras获取数组中的输出值,python,keras,Python,Keras,我是python和Keras的初学者。我将Keras与tensorflow后端一起使用。我想从Keras中的每个层(隐藏层和输出层)获取数组中的值。我怎么做 这是我的顺序模型 def baseline_model(): # create model model = Sequential() model.add(Conv2D(32, (5, 5), input_shape=(1, 28, 28), activation='relu')) model.add(MaxPooling2D(pool_si
def baseline_model():
# create model
model = Sequential()
model.add(Conv2D(32, (5, 5), input_shape=(1, 28, 28), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation=tempsigmoid))
# Compile model
model.compile(loss='mse', optimizer='adam', metrics=['accuracy'])
return model
# build the model
model = baseline_model()
我试过使用这个代码
hidden_layer = model.layers[4].output
print(hidden_layer)
但结果是张量
Tensor("dense_1/Relu:0", shape=(?, 128), dtype=float32)
要提取神经网络的第i层,可以使用Keras函数。 假设您正在对某个数据
df
进行模型的培训:
from tensorflow.keras import backend as K
# create a Keras function to get i-th layer
get_layer_output = K.function(inputs = Model.layers[0].input, outputs = Model.layers[i].output)
# extract output
layer_output = get_layer_output(df)
你可以找到一个实际的应用。希望这有帮助,否则请告诉我。要提取神经网络的第i层,可以使用Keras函数。
假设您正在对某个数据df
进行模型的培训:
from tensorflow.keras import backend as K
# create a Keras function to get i-th layer
get_layer_output = K.function(inputs = Model.layers[0].input, outputs = Model.layers[i].output)
# extract output
layer_output = get_layer_output(df)
你可以找到一个实际的应用。希望这有帮助,否则请告诉我。您也可以做同样的事情,但用这种方式保存数据:
hidden_layer = model.layers[4].output
hidden_layer = hidden_layer.eval(session=tf.Session())
print(hidden_layer)
这将直接将张量数据保存在hidden_layer变量中。您可以执行相同的操作,但使用这种方式保存数据:
hidden_layer = model.layers[4].output
hidden_layer = hidden_layer.eval(session=tf.Session())
print(hidden_layer)
这将直接将张量数据保存在隐藏层变量中。感谢您的响应。我尝试并得到错误消息AttributeError:“Conv2D”对象没有属性“inputs”
。可能是因为我的模型是卷积的吗?阅读你的错误信息。。。你写了<代码>输入>代码>而不是<代码>输入<代码>吗?这是正确的方式,应该被标记为最终解决方案。solved@Leevo非常感谢。我已经修改了我的代码,但它仍然得到错误TypeError:
inputs`到TensorFlow后端函数应该是一个列表或元组。`我现在正在计算,谢谢您的回复。我尝试并得到错误消息AttributeError:“Conv2D”对象没有属性“inputs”
。可能是因为我的模型是卷积的吗?阅读你的错误信息。。。你写了<代码>输入>代码>而不是<代码>输入<代码>吗?这是正确的方式,应该被标记为最终解决方案。solved@Leevo非常感谢。我已经修改了我的代码,但它仍然得到错误TypeError:
inputs`到TensorFlow后端函数应该是一个列表或元组。`我现在正在计算它