這篇文章將為大家詳細講解有關keras特征圖可視化的示例分析,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
使用的比較簡單的一個模型:
def simple_cnn(): input_data = Input(shape=(28, 28, 1)) x = Conv2D(64, kernel_size=3, padding='same', activation='relu', name='conv1')(input_data) x = MaxPooling2D(pool_size=2, strides=2, name='maxpool1')(x) x = Conv2D(32, kernel_size=3, padding='same', activation='relu', name='conv2')(x) x = MaxPooling2D(pool_size=2, strides=2, name='maxpool2')(x) x = Dropout(0.25)(x) # 獲得最后一層卷積層的輸出 # 添加自己的全連接 x = Flatten(name='flatten')(x) x = Dense(128, activation='relu', name='fc1')(x) x = Dropout(0.25)(x) x = Dense(10, activation='softmax', name='fc2')(x) model = Model(inputs=input_data, outputs=x)
此模型已經訓練好了,跑了10個epoch,驗證集0.33

這里的效果還是很好的,┓( ´?` )┏
下面在網上搞了張手寫數字

使用網絡進行預測,這里就先給出如何可視化第一層的卷積層的輸出吧,哇哈哈
代碼:
input_data = Input(shape=(28, 28, 1))
x = Conv2D(64, kernel_size=3, padding='same', activation='relu', name='conv1')(input_data)
x = MaxPooling2D(pool_size=2, strides=2, name='maxpool1')(x)
x = Conv2D(32, kernel_size=3, padding='same', activation='relu', name='conv2')(x)
x = MaxPooling2D(pool_size=2, strides=2, name='maxpool2')(x)
x = Dropout(0.25)(x)
x = Flatten(name='flatten')(x)
x = Dense(128, activation='relu', name='fc1')(x)
x = Dropout(0.25)(x)
x = Dense(10, activation='softmax', name='fc2')(x)
model = Model(inputs=input_data, outputs=x)
model.load_weights('final_model_mnist_2019_1_28.h6')
raw_img = cv2.imread('test.png')
test_img = load_img('test.png', color_mode='grayscale', target_size=(28, 28))
test_img = np.array(test_img)
test_img = np.expand_dims(test_img, axis=0)
test_img = np.expand_dims(test_img, axis=3)
conv1_layer = Model(inputs=input_data, outputs=model.get_layer(index=1).output)
conv1_output = conv1_layer.predict(test_img)
for i in range(64):
show_img = conv1_output[:, :, :, i]
print(show_img.shape)
show_img.shape = [28,28]
cv2.imshow('img', show_img)
cv2.waitKey(0)核心方法就是通過加載模型后,新建Model,將輸出部分換為你想要查看的網絡層數即可,當然get_layer()包括了name和index兩個參數。最后通過遍歷當前卷積層的所有特征映射,將每一個都展示出來。就可以了。

關于“keras特征圖可視化的示例分析”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。