注意力可视化代码

读取网络层输出的特征到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 = arr
        if 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:37

import matplotlib.pyplot as plt
import numpy as np


def 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_array


def 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 np
    data_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)

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yokon_D

您的鼓励将是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值