(废弃)查看卷积特征图结果,权重、偏置(model版)

概述

本文介绍查看 卷积特征图结果,权重、偏置量

准备图片

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

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

代码

导入模块

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

读取图片

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)

获取特征图

img_batch = np.expand_dims(img, axis=0)
print('输入图shape:',img_batch.shape)

#新建为model,设置一个输入,两个输出,分别是卷积层和池化层
out_model = Model(inputs=model.input,outputs=[model.layers[0].output,model.layers[1].output])


"""
执行运算输出特征图
out_model的输出是两个,所以此处输出的特征图也是两个
"""
out_img = out_model.predict(img_batch)

# print ("特征图 shape:",out_img.shape)
print ("特征图:\n",out_img)

定义显示图片的函数


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('row,col',row,col)

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

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