利用训练好的神经网络权重画热力图

这里以YOLOv8举例

import warnings
warnings.filterwarnings('ignore')
warnings.simplefilter('ignore')
import torch, yaml, cv2, os, shutil, sys
import numpy as np
np.random.seed(0)
import matplotlib.pyplot as plt
from tqdm import trange
from PIL import Image
from ultralytics.nn.tasks import attempt_load_weights
from ultralytics.utils.torch_utils import intersect_dicts
from ultralytics.utils.ops import xywh2xyxy, non_max_suppression
from pytorch_grad_cam import GradCAMPlusPlus, GradCAM, XGradCAM, EigenCAM, HiResCAM, LayerCAM, RandomCAM, EigenGradCAM
from pytorch_grad_cam.utils.image import show_cam_on_image, scale_cam_image
from pytorch_grad_cam.activations_and_gradients import ActivationsAndGradients

def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
    # Resize and pad image while meeting stride-multiple constraints
    shape = im.shape[:2]  # current shape [height, width]
    if isinstance(new_shape, int):
        new_shape = (new_shape, new_shape)

    # Scale ratio (new / old)
    r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
    if not scaleup:  # only scale down, do not scale up (for better val mAP)
        r = min(r, 1.0)

    # Compute padding
    ratio = r, r  # width, height ratios
    new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
    dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]  # wh padding
    if auto:  # minimum rectangle
        dw, dh = np.mod(dw, stride), np.mod(dh, stride)  # wh padding
    elif scaleFill:  # stretch
        dw, dh = 0.0, 0.0
        new_unpad = (new_shape[1], new_shape[0])
        ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]  # width, height ratios

    dw /= 2  # divide padding into 2 sides
    dh /= 2

    if shape[::-1] != new_unpad:  # resize
        im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
    top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
    left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
    im = cv2.copyMakeBorder(im
### 使用 Python 和 BP 神经网络生成力图 BP(Backpropagation)神经网络是一种常用的前馈人工神经网络模型,通过反向传播算法训练权重参数。为了生成力图,可以利用 BP 网络中的隐藏层激活值作为输入特征的空间分布表示,并将其映射为二维矩阵形式。 以下是实现方法及其代码示例: #### 方法概述 1. **构建并训练 BP 神经网络**:使用 `TensorFlow` 或 `PyTorch` 构建一个简单的 BP 网络,并完成数据集上的训练过程。 2. **提取中间层激活值**:在网络推理阶段,记录特定隐藏层的激活值,这些值反映了输入样本在该层的响应情况。 3. **生成力图**:将激活值转化为二维数组,并应用颜色映射函数生成可视化的力图。 --- #### 实现代码示例 以下是一个基于 TensorFlow 的简单实现案例: ```python import numpy as np import matplotlib.pyplot as plt from tensorflow.keras.models import Model from tensorflow.keras.layers import Dense, Input from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler # 数据准备 X, y = make_classification(n_samples=1000, n_features=20, random_state=42) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test) # 定义 BP 神经网络结构 input_layer = Input(shape=(20,)) hidden_layer_1 = Dense(16, activation='relu')(input_layer) # 隐藏层用于生成力图 output_layer = Dense(1, activation='sigmoid')(hidden_layer_1) model = Model(inputs=input_layer, outputs=output_layer) model.compile(optimizer='adam', loss='binary_crossentropy') # 训练模型 model.fit(X_train_scaled, y_train, epochs=10, batch_size=32, verbose=0) # 提取隐藏层激活值 activation_model = Model(inputs=model.input, outputs=model.get_layer('dense').output) activations = activation_model.predict(X_test_scaled[:1]) # 取第一个测试样本来生成力图 # 调整形状以便绘 heatmap_data = activations.reshape((4, 4)) # 假设我们希望显示为 4x4 的网格 # 绘制力图 plt.figure(figsize=(6, 6)) plt.imshow(heatmap_data, cmap='hot', interpolation='nearest') plt.colorbar(label="Activation Value") plt.title("Heatmap of Hidden Layer Activations", fontsize=14) plt.show() # 保存力图为文件 plt.savefig("neural_network_heatmap.png") ``` --- #### 关键点说明 1. **数据预处理**:标准化输入数据有助于提高 BP 网络的学习效率[^1]。 2. **隐藏层选择**:通常选取靠近输出层的一个隐藏层,因为其激活值更能反映全局模式。 3. **力图绘制工具**:这里采用 Matplotlib 库中的 `imshow()` 函数来展示二维数组的颜色变化趋势[^2]。 --- #### 注意事项 - 如果输入维度较高,则需先降维再生成力图,常用技术有 PCA 或 t-SNE。 - 对于更复杂的 CNN 结构,可借鉴 Grad-CAM 技术定位重要区域[^3]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值