You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何查看并可视化Keras模型的中间层?以KerasMNIST预训练CNN为例

可视化Keras预训练CNN中间层输出的步骤

没问题!要可视化你提到的那个预训练MNIST CNN模型的中间层特征,咱们可以按下面的步骤来操作,步骤清晰易上手:

1. 加载预训练模型

首先得把你的预训练模型加载进来,确保你已经保存了模型文件(比如.h5格式):

from keras.models import load_model

# 替换成你的模型文件路径
model = load_model('path/to/your/pretrained_model.h5')

2. 构建特征提取模型

接下来,我们需要创建一个新的模型,它会以原模型的输入为输入,输出你想要可视化的中间层的特征图。根据你给出的模型结构,比如可以选择conv2d_1、conv2d_2、max_pooling2d_1这些层:

from keras.models import Model

# 这里列出你想可视化的层名,根据你的模型结构调整
target_layer_names = ['conv2d_1', 'conv2d_2', 'max_pooling2d_1']

# 构建特征提取器
feature_extractor = Model(
    inputs=model.input,
    outputs=[model.get_layer(layer_name).output for layer_name in target_layer_names]
)

3. 准备输入样本

选一张MNIST的测试图片作为输入,记得要和模型训练时的预处理方式保持一致:

import numpy as np
from keras.datasets import mnist

# 加载MNIST数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()

# 预处理:添加通道维度+归一化
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1).astype('float32') / 255

# 选第一张测试图作为样本(你也可以选其他图片)
sample_image = x_test[0:1]  # 保持batch维度,模型需要4D输入

4. 提取中间层特征

用刚才构建的特征提取器,得到目标层的特征图:

# 预测得到各层的特征输出
layer_features = feature_extractor.predict(sample_image)

5. 可视化特征图

最后用Matplotlib把每个层的特征图画出来,直观看到中间层的学习效果:

import matplotlib.pyplot as plt

for idx, (layer_name, features) in enumerate(zip(target_layer_names, layer_features)):
    plt.figure(figsize=(16, 16))
    plt.suptitle(f'Feature Maps from Layer: *{layer_name}*', fontsize=18)
    
    # 计算特征图的行列数,让布局更美观
    num_features = features.shape[-1]
    rows = int(np.sqrt(num_features))
    cols = num_features // rows
    
    # 逐个绘制特征图
    for feature_idx in range(num_features):
        plt.subplot(rows, cols, feature_idx + 1)
        # 用灰度图显示,也可以换成'viridis'等彩色配色
        plt.imshow(features[0, :, :, feature_idx], cmap='gray')
        plt.axis('off')  # 关闭坐标轴,聚焦特征图
    
    plt.tight_layout()
    plt.show()

一些小提示

  • 如果你的模型层名和示例里的不一样,一定要修改target_layer_names里的内容,和模型结构中的层名完全匹配
  • 如果你用自己的图片而不是MNIST样本,要确保图片的尺寸、通道数、归一化方式和训练时一致
  • 可以更换cmap参数(比如cmap='viridis'),用彩色来观察特征图的细节差异

内容的提问来源于stack exchange,提问作者Eka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:07:54