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]

 

效果應該是一樣的。

---------------------
作者:哈哈進步
來源:CSDN
原文:https://blog.csdn.net/hahajinbu/article/details/77982721
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM