当前位置: 首页 > news >正文

python第35天打卡

 

三种不同的模型可视化方法:推荐torchinfo打印summary+权重分布可视化
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
from torchinfo import summary
import numpy as np# 1. 定义示例模型
class CNN(nn.Module):def __init__(self):super().__init__()self.conv_layers = nn.Sequential(nn.Conv2d(3, 16, kernel_size=3),nn.ReLU(),nn.MaxPool2d(2),nn.Conv2d(16, 32, kernel_size=3),nn.ReLU(),nn.MaxPool2d(2))self.fc_layers = nn.Sequential(nn.Linear(32*6*6, 128),nn.ReLU(),nn.Linear(128, 10))def forward(self, x):x = self.conv_layers(x)x = torch.flatten(x, 1)x = self.fc_layers(x)return xmodel = CNN()# 2. 模型摘要可视化 (使用torchinfo)
print("\n=== 模型结构摘要 ===")
summary(model, input_size=(1, 3, 32, 32),  # (batch, channels, height, width)col_names=["input_size", "output_size", "num_params", "kernel_size"],verbose=1
)# 3. 权重分布可视化
def plot_weight_distribution(model):plt.figure(figsize=(12, 6))# 收集所有权重all_weights = []for name, param in model.named_parameters():if 'weight' in name:flattened = param.detach().cpu().numpy().flatten()all_weights.extend(flattened)# 绘制直方图plt.hist(all_weights, bins=150, alpha=0.7, color='blue', edgecolor='black')plt.title('Model Weights Distribution')plt.xlabel('Weight Value')plt.ylabel('Frequency (log scale)')plt.yscale('log')plt.grid(True, alpha=0.3)plt.show()print("\n=== 权重分布图 ===")
plot_weight_distribution(model)# 4. 逐层权重可视化 (额外方法)
def plot_layer_weights(model):plt.figure(figsize=(15, 10))for i, (name, param) in enumerate(model.named_parameters()):if 'weight' in name:plt.subplot(3, 3, i+1)layer_weights = param.detach().cpu().numpy().flatten()plt.hist(layer_weights, bins=100, alpha=0.7)plt.title(f'{name} weight distribution')plt.grid(True, alpha=0.2)plt.tight_layout()plt.show()print("\n=== 逐层权重分布 ===")
plot_layer_weights(model)# 5. 权重矩阵可视化 (额外方法)
def visualize_weight_matrix(model):plt.figure(figsize=(15, 4))# 获取第一个卷积层的权重conv1_weight = model.conv_layers[0].weight.detach().cpu()# 归一化权重用于显示min_val = torch.min(conv1_weight)max_val = torch.max(conv1_weight)normalized_weights = (conv1_weight - min_val) / (max_val - min_val)# 绘制权重矩阵for i in range(16):  # 显示前16个卷积核plt.subplot(2, 8, i+1)plt.imshow(normalized_weights[i].permute(1, 2, 0))  # CHW -> HWCplt.axis('off')plt.title(f'Kernel {i+1}')plt.suptitle('First Conv Layer Kernels', fontsize=16)plt.tight_layout()plt.show()print("\n=== 卷积核可视化 ===")
visualize_weight_matrix(model)

 

@浙大疏锦行
http://www.xdnf.cn/news/693361.html

相关文章:

  • RISC-V 开发板 MUSE Pi Pro 搭建 Spacengine AI模型部署环境
  • 联软SDP+安渡:收敛暴露面 从生产网自动取数 安全高效
  • 班级管理系统
  • Python+Flask+Html做一个简单的测试联调工具
  • 链路追踪神器zipkin安装详细教程教程
  • C语言中:递归问题的深入研究
  • mp中的密码处理
  • 数据分析的方法总结
  • 工业控制核心引擎高性能MCU——MM32F5370
  • 【教程】服务器如何防止GET/SYN洪泛攻击
  • C++ 模板元编程语法大全
  • 如何在使用kickstart安装物理机操作系统的过程中核对服务器的SN
  • Docker容器启动失败的常见原因分析
  • 每日C++ 5.28dddd
  • FreeCAD如何对器件表面逐面着色
  • 单点登陆(SSO)简介-笔记
  • style scoped作用域
  • RabbitMQ性能调优:关键技术、技巧与最佳实践
  • Vert.x学习笔记-什么是Context
  • Linux `less` 命令深度解析与高阶应用指南
  • python网络编程之socket
  • 面试高频图论题『墙与门』:Swift BFS 解法全流程拆解
  • node_modules\node-sass: Command failed.报错了
  • DeepSeek 赋能教育新生态,智能教育机器人开启智慧教学新篇章
  • RuoYi前后端分离框架将前端dist资源集成到Jar包中独立部署
  • 考研系列-操作系统:第二章、进程与线程
  • Java垃圾回收器全面解析:原理、参数、对比与实战调优
  • 用QT写一个车速表
  • 台式电脑CPU天梯图_2025年台式电脑CPU天梯图
  • PortSwigger-03-点击劫持