1. 程式人生 > 程式設計 >keras得到每層的係數方式

keras得到每層的係數方式

使用keras搭建好一個模型,訓練好,怎麼得到每層的係數呢:

weights = np.array(model.get_weights())
print(weights)
print(weights[0].shape)
print(weights[1].shape)

這樣係數就被存放到一個np中了。

補充知識:使用keras框架編寫的深度模型 輸出及每一層的特徵視覺化

使用訓練好的模型進行預測的時候,為分析效果,通常需要對特徵提取過程中的特徵對映做視覺化操作

本文以keras為例,對特徵視覺化操作進行詳解。

一、首先,對模型的最後輸出層進行特徵視覺化

from keras import models
#使用matlpotlib模組進行繪圖的操作
import matplotlib.pylot as plt
#images是一個batch的輸入影象,batch_input[batch影象數量,尺寸高,尺寸寬,3(rgb通道數量)]
#model是訓練好的模型
#model = load_model('path')
nb_images = len(images)
batch_input = np.zeros((nb_images,net_h,net_w,3))

# preprocess the input
for i in range(nb_images):
 batch_input[i] = preprocess_input(images[i],net_w)  

# run the prediction
#batch_output為一個樣本的所有通道輸出特徵對映,本文應用特徵金字塔結構,有三個維度的特徵提取層
#batch_output[0]是第一個維度的特徵提取層所有通道的輸出特徵對映,四維,本文例子中為[1,52,72]
#[一個樣本,尺寸,尺寸,通道數]

#也可以是batch_output = model.predict(batch_input)
batch_output = model.predict_on_batch(batch_input)
batch_boxes = [None]*nb_images
print(batch_output[0].shape)
#display feature map

#下面為歸一化到0-255空間內
xx = batch_output[0]
max = np.max(xx)
print(max,"max value is :")
X_output = X_output .astype("float32") / max * 255

#下面的30為第30個通道
X_output = xx[0,:,30]

#使用matplotlib顯示影象
plt.figure()
plt.imshow(X_output,cmap='viridis')
plt.show()

#輸出結果

原始影象

keras得到每層的係數方式

輸出層的特徵視覺化

keras得到每層的係數方式

二、視覺化某一層的特徵對映

from keras import backend as k
from keras import models
import matplotlib.pylot as plt
model = load_model('...')
layer_1 =k.function([model.layers[0].input],[model.layers[1].output])

#第2個model,layers[]改成你想顯示的層數
f1 = layer_1[input_image][0]
f1.image = f1[0,channel]
plt,matshow(f1.image,camp='viridis')
plt.show()

示例:

from keras import models
import matplotlib.pylot as plt
from keras import backend as k
#images是一個batch的輸入影象,batch_input[batch影象數量,尺寸高,尺寸寬,3(rgb通道數量)]
#model是訓練好的模型
#model = load_model('path')
nb_images = len(images)
batch_input = np.zeros((nb_images,net_w)  
#display feature map

#視覺化第一層的特徵對映
layer_1 = K.function([model.layers[0].input],[model.layers[1].output])
f1 = layer_1([batch_input])[0]
print(f1.shape)
max = np.max(f1)
f1 =f1.astype("float32") / max * 255
plt.figure()

#顯示第一層網路前5個通道的特徵對映
for i in range(5):
 plt.subplot(2,3,i+1)
 plt.imshow(f1[0,i],cmap='viridis')
plt.show()

輸出結果:

keras得到每層的係數方式

以上這篇keras得到每層的係數方式就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。