这篇教程Keras 获取深度学习模型中某一层输出写得很实用,希望能帮到您。
Keras 获取中间某一层输出
1.使用函数模型API,新建一个model,将输入和输出定义为原来的model的输入和想要的那一层的输出,然后重新进行predict.
1 #coding=utf-8
2 import seaborn as sbn
3 import pylab as plt
4 import theano
5 from keras.models import Sequential
6 from keras.layers import Dense,Activation
7
8
9 from keras.models import Model
10
11 model = Sequential()
12 model.add(Dense(32, activation='relu', input_dim=100))
13 model.add(Dense(16, activation='relu',name="Dense_1"))
14 model.add(Dense(1, activation='sigmoid',name="Dense_2"))
15 model.compile(optimizer='rmsprop',
16 loss='binary_crossentropy',
17 metrics=['accuracy'])
18
19 # Generate dummy data
20 import numpy as np
21 #假设训练和测试使用同一组数据
22 data = np.random.random((1000, 100))
23 labels = np.random.randint(2, size=(1000, 1))
24
25 # Train the model, iterating on the data in batches of 32 samples
26 model.fit(data, labels, epochs=10, batch_size=32)
27 #已有的model在load权重过后
28 #取某一层的输出为输出新建为model,采用函数模型
29 dense1_layer_model = Model(inputs=model.input,
30 outputs=model.get_layer('Dense_1').output)
31 #以这个model的预测值作为输出
32 dense1_output = dense1_layer_model.predict(data)
33
34 print dense1_output.shape
35 print dense1_output[0]
36
37
38 2.因为我的后端是使用的theano,所以还可以考虑使用theano的函数:
39 #这是一个theano的函数
40 dense1 = theano.function([model.layers[0].input],model.layers[1].output,allow_input_downcast=True)
41 dense1_output = dense1(data) #visualize these images's FC-layer feature
42 print dense1_output[0]  深度学习中标签、有监督学习、回归等概念通俗解释 Keras实现卷积神经网络(CNN)可视化 |