读取网络层输出的特征到txt文件,arr为文件名
def hot(self, feature, arr):# 在第二维(通道维)上相加summed_tensor = torch.sum(feature, dim=1, keepdim=True) # 结果形状为 [1, 1, 64, 64]selected_matrix = summed_tensor.squeeze(1) # 移除单维度selected_matrix_np = selected_matrix.cpu().numpy()txt_name = arrif selected_matrix_np[0].ndim == 2:# 二维数组,写入每一行with open(txt_name, 'w') as f:for row in selected_matrix_np[0]:row_str = ' '.join(map(str, row)) # 将每个元素转换为字符串并加空格分隔f.write(row_str + '\n')
生成热力图
# -*- encoding: utf-8 -*-
# @ModuleName: hot
# @Function: txt热力图生成
# @Author: Yokon
# @Time: 2024/5/17 下午9:37import matplotlib.pyplot as plt
import numpy as npdef up(original_array):expanded_array = np.zeros((512, 512))x_indices = np.linspace(0, 63, 512)y_indices = np.linspace(0, 63, 512)for i in range(512):for j in range(512):expanded_array[i, j] = original_array[int(x_indices[i]), int(y_indices[j])]return expanded_arraydef txt_to_img(filename):# 假设文本文件中的数据是空格分隔的,每行代表一个矩阵的一行# filename = 'T2.txt'data = []with open(filename, 'r') as file:for line in file:# 移除行尾的换行符并分割字符串为数值列表row_data = [float(x) for x in line.strip().split()]data.append(row_data)import numpy as npdata_array = np.array(data)data_array = up(data_array)plt.figure(figsize=(512, 512)) plt.title('Heatmap from Text Data') plt.imshow(data_array, cmap='jet', interpolation='nearest') cbar = plt.colorbar() cbar.set_ticks([-10, 0, 10, 20, 30, 40])cbar.set_ticklabels(['-10', '0', '10', '20', '30', '40'])plt.xticks(range(data_array.shape[1]), [f'Col{i}' for i in range(data_array.shape[1])]) plt.yticks(range(data_array.shape[0]), [f'Row{i}' for i in range(data_array.shape[0])]) plt.axis('off')plt.show()if __name__=='__main__':txt_name = 'T1.txt'txt_to_img(txt_name)