查看卷积特征图结果,权重、偏置(backend)

概述

本文介绍用 tensorflow.keras.backend.function方式,查看 卷积特征图结果,权重、偏置量

准备图片

为了便于人眼查看,采用下面16*16的小图:

将上面16*16单通道图下载到本地

代码

导入模块

# coding: utf-8
from tensorflow.keras import Sequential
from tensorflow.keras import Model
from tensorflow.keras.layers import Conv2D, MaxPool2D
from tensorflow.keras.layers import Activation

import matplotlib.pyplot as plt
from pylab import *

from PIL import Image
import numpy as np

from tensorflow.keras.backend import function

读取图片

path=r"C:\Users\mym\Desktop\文件接收柜\feiji.jpg"
im = Image.open(path)
img=np.array(im)
print('输入图shape:',img.shape)
print('输入图:',img)
img=img.reshape(img.shape[0],img.shape[1],1)
# img=np.expand_dims(img,-1)
print(img.shape)
# print(img)

建模


model = Sequential()
# 第一层CNN
# 第一个参数是卷积核的数量,第二三个参数是卷积核的大小
model.add(Conv2D(2, (3, 3), input_shape=img.shape))
# 为了简单,激活层注释掉
# model.add(Activation('relu'))
model.add(MaxPool2D(pool_size=(4, 4)))

    # 第二层CNN
#     model.add(Conv2D(9, (5, 5), input_shape=img_shape))
#     model.add(Activation('relu'))
#     model.add(MaxPool2D(pool_size=(3, 3)))

#     # # # 第三层CNN
#     model.add(Conv2D(9, (5, 5), input_shape=img_shape))
#     model.add(Activation('relu'))
#     model.add(MaxPool2D(pool_size=(2, 2)))

#     # # # 第四层CNN
#     model.add(Conv2D(9, (3, 3), input_shape=img_shape))
#     model.add(Activation('relu'))
#     model.add(MaxPool2D(pool_size=(2, 2)))
model.summary()

查看权重

w,b=model.layers[0].get_weights()
print(w)
print(w.shape)
print(b)

获取特征图

input_image = np.expand_dims(img, axis=0)
print('input_image.shape',input_image.shape)

print('len(model.layers)::',len(model.layers))

"""
第一个参数为输入层,list类型,model.layers[0],不修改,表示输入数据;
第二个参数为输出层,list类型,model.layers[you wanted],修改为要输出的层数的编号
输入层、输出层之间的层都会执行
"""
fun = function([model.layers[0].input], [model.layers[0].output,model.layers[1].output])
print(type(fun))
print(fun.__dict__)

"""
传入inpu_image,进行运算,返回特征图像矩阵
其shape中,中间两个是特征图像高、宽,最后一个是特征图数量
"""
out_img = fun([[input_image]])
out_img
# out_img.shape

定义显示图片的函数

def get_row_col(num_pic):
    squr = num_pic ** 0.5
    row = round(squr)
    col = row + 1 if squr - row > 0 else row
    return row, col

def show_img(out_img):
    print("out_img type::",type(out_img))
    num_pic = out_img.shape[-1]
    row, col = get_row_col(num_pic)

    print('out_img.shape:',out_img.shape)

    #显示将特征图
    for _ in range(num_pic):
            show_img = out_img[:, :, :, _]
            show_img.shape = out_img.shape[1:3]
            plt.subplot(row, col, _ + 1)
            plt.imshow(show_img, cmap='gray')
            # plt.imshow(show_img)
            plt.axis('off')
            print('结果图像-----')
            print(show_img)

    plt.show()

显示特征图

# 显示卷积后的特征图
show_img(out_img[0])

# 显示池化后的特征图
show_img(out_img[1])

感谢:
https://blog.csdn.net/u010420283/article/details/80303231
https://blog.csdn.net/dcrmg/article/details/81255498
https://www.cnblogs.com/tectal/p/9426971.html


原文出处:/show_1EF4B80bKdEG.html