keras得到每层的系数方式

(编辑:jimmy 日期: 2025/9/30 浏览:2)

使用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_h, net_w)  

# run the prediction
#batch_output为一个样本的所有通道输出特征映射,本文应用特征金字塔结构,有三个维度的特征提取层
#batch_output[0]是第一个维度的特征提取层所有通道的输出特征映射,四维,本文例子中为[1, 52, 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_h, net_w, 3))

# preprocess the input
for i in range(nb_images):
 batch_input[i] = preprocess_input(images[i], net_h, 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得到每层的系数方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

一句话新闻

一文看懂荣耀MagicBook Pro 16
荣耀猎人回归!七大亮点看懂不只是轻薄本,更是游戏本的MagicBook Pro 16.
人们对于笔记本电脑有一个固有印象:要么轻薄但性能一般,要么性能强劲但笨重臃肿。然而,今年荣耀新推出的MagicBook Pro 16刷新了人们的认知——发布会上,荣耀宣布猎人游戏本正式回归,称其继承了荣耀 HUNTER 基因,并自信地为其打出“轻薄本,更是游戏本”的口号。
众所周知,寻求轻薄本的用户普遍更看重便携性、外观造型、静谧性和打字办公等用机体验,而寻求游戏本的用户则普遍更看重硬件配置、性能释放等硬核指标。把两个看似难以相干的产品融合到一起,我们不禁对它产生了强烈的好奇:作为代表荣耀猎人游戏本的跨界新物种,它究竟做了哪些平衡以兼顾不同人群的各类需求呢?