矩阵热图】】
一、基础热图绘制
import matplotlib.pyplot as plt
import numpy as np
# 模拟数据生成
matching_history = [np.random.randint(0, 2, (5, 3)) for _ in range(4)] # 5个UE,3个边缘服务器,4次迭代
# 绘制最终匹配矩阵
plt.figure(figsize=(10, 6))
plt.imshow(matching_history[-1], cmap='Blues', interpolation='nearest')
plt.colorbar(label='Connection Strength')
plt.xticks(range(3), [f'Edge {i}' for i in range(3)]) # 自定义X轴标签
plt.yticks(range(5), [f'UE {i}' for i in range(5)]) # 自定义Y轴标签
plt.xlabel('Edge Server')
plt.ylabel('UE')
plt.title('Final UE-Edge Matching Matrix')
plt.grid(False) # 关闭默认网格线
plt.show()
二、训练过程动态可视化
1. 多阶段对比(子图模式)
plt.figure(figsize=(12, 8))
for i in range(4):
plt.subplot(2, 2, i+1)
plt.imshow(matching_history[i], cmap='OrRd', vmin=0, vmax=1) # 固定颜色范围
plt.title(f'Iteration {i+1}')
plt.axis('off') # 隐藏坐标轴
plt.tight_layout()
plt.show()
2. 实时更新(适合Jupyter环境)
from IPython import display
for epoch in range(10):
# 模拟训练过程生成新矩阵
new_matrix = np.random.randint(0, 2, (5, 3))
matching_history.append(new_matrix)
# 实时更新绘图
plt.clf()
plt.imshow(new_matrix, cmap='viridis', alpha=0.8)
plt.title(f'Training Epoch {epoch+1}')
display.clear_output(wait=True)
display.display(plt.gcf())
三、高级技巧
1. 添加数值标注
matrix = matching_history[-1]
plt.imshow(matrix, cmap='Pastel1')
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
plt.text(j, i, f'{matrix[i,j]:.2f}', ha='center', va='center', color='red')
plt.colorbar()
2. 自定义颜色分级
from matplotlib.colors import BoundaryNorm
bounds = [0, 0.3, 0.7, 1]
cmap = plt.get_cmap('PiYG')
norm = BoundaryNorm(bounds, cmap.N)
plt.imshow(matrix, cmap=cmap, norm=norm)
plt.colorbar(ticks=bounds)
3. 保存高清图片
plt.savefig('matching_matrix.png', dpi=300, bbox_inches='tight')
四、结合训练逻辑
假设使用强化学习训练匹配策略:
# 伪代码示例
import time
matching_history = []
for episode in range(100):
# 1. 执行训练逻辑生成匹配矩阵
current_matrix = your_model.train_step()
# 2. 记录历史数据
matching_history.append(current_matrix.copy())
# 3. 每10步可视化一次
if episode % 10 == 0:
plt.cla() # 清除当前轴
plt.imshow(current_matrix, cmap='coolwarm')
plt.title(f'Training Progress - Episode {episode}')
plt.pause(0.1) # 需要plt.ion()开启交互模式
plt.ioff() # 关闭交互模式
五、学习路径建议
-
掌握Matplotlib基础
- 官方教程:Matplotlib Tutorial
- 重点学习:
subplots
,imshow
,colorbar
, 文本标注
-
理解矩阵数据
- 学习使用NumPy生成测试数据
- 了解不同归一化方法对热图的影响
-
探索高级可视化
- 交互式可视化:Plotly库
- 三维矩阵可视化:
mplot3d
工具包
-
结合领域知识
- 根据具体场景调整颜色映射
- 添加网络拓扑图等辅助信息
通过以上方法,你可以逐步实现:
- 实时观察训练动态
- 多维度对比实验结果
- 生成出版级质量的插图
- 直观分析算法性能
关键是多实践不同数据场景,尝试调整各种可视化参数,观察效果变化。