神经网络中间层特征图可视化(输入为音频)(二)

相比方法一个人感觉这种方法更好

复制代码
import librosa
import numpy as np
import utils
import torch
import matplotlib.pyplot as plt

class Hook:
    def __init__(self):
        self.features = None

    def hook_fn(self, module, input, output):
        self.features = output

# 创建钩子的实例
hook = Hook()

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def extract_mbe(_y, _sr, _nfft, _nb_mel):
    #梅尔频谱
    spec = librosa.core.spectrum._spectrogram(y=_y, n_fft=_nfft, hop_length=_nfft // 2, power=1)[0]
    mel_basis = librosa.filters.mel(sr=_sr, n_fft=_nfft, n_mels=_nb_mel)
    mel_spec = np.log(np.dot(mel_basis, spec).T)
    return mel_spec       #最后必须是[frames, dimensions]

def preprocess_data(X, seq_len, nb_ch):
    # split into sequences
    X = utils.split_in_seqs(X, seq_len)
    X = utils.split_multi_channels(X, nb_ch)
    # Convert to PyTorch tensors
    X = torch.Tensor(X)
    X = X.permute(0,1,3,2)   #x形状为[709,2,40,256],【总样本数,通道数,特征维度,像素宽度】
    return X

# 提取梅尔频谱特征
audio_path = "a011.wav"
y, sr = librosa.load(audio_path, sr=44100)
mel = extract_mbe(y, sr, 2048, 64)

value = preprocess_data(mel, 256, 1).to(device)     #value 为输入模型的样本特征


model = torch.load(f'best_model_2.pth')

# 将钩子注册到需要的层
model.cnn1.register_forward_hook(hook.hook_fn)

# 假设`input_data`是你的输入张量
output = model(value)

# 访问存储的特征
retnet_features = hook.features
#print(retnet_features.shape)
# 可视化特征(假设retnet_features是一个张量)
retnet_features = retnet_features.permute(0, 2, 1, 3)
#retnet_features = retnet_features.transpose(1, 2)
#print(retnet_features.shape)
retnet_features = torch.cat([retnet_features[i] for i in range(10)], dim=2)
#print(retnet_features.shape)

# 可视化批次中第一个样本的特定通道
plt.imshow(retnet_features.sum(1).detach().cpu().numpy(), cmap='viridis', origin='lower')   #[高,通道, 宽]
# plt.imshow(retnet_features.detach().cpu().numpy(), cmap='viridis', origin='lower')   #[高,宽]
plt.show()
相关推荐
打工仔折腾 AI10 小时前
在 Ubuntu ARM64 部署 Q1 V3.0 MuJoCo 模型:加载、单步推理与执行器响应解析
linux·运维·人工智能·python·深度学习·ubuntu·性能优化
feasibility.15 小时前
不装Claude Code,WorkBuddy也能做视频,Remotion skill告别抽卡(含安装与使用)
人工智能·aigc·音视频·agi·skill·remotion·workbuddy
陈嘿萌16 小时前
Fusion Anything Model:面向通用多模态融合的基座模型
图像处理·人工智能·深度学习·计算机视觉·学术研究与理论基础
老鱼说AI16 小时前
SNN脉冲神经网络:全连接、卷积与循环SNN
人工智能·深度学习·神经网络·机器学习·自然语言处理
程序猿编码16 小时前
纯 C++ 手写 LLM 推理引擎:分页 KV 缓存、连续批、多卡张量并行全部内置
c++·深度学习·缓存·大模型推理·自动微分·模型推理
在所不辞兄17 小时前
【零基础学智能仿真-62】从应变—应力计算弹性常数
人工智能·深度学习·神经网络·机器学习·有限元·智能仿真
STLearner17 小时前
KDD 2026 | (2月轮)时空数据(Spatial-Temporal)论文总结时空【下】(人群移动,城市科学(资源调度,)
大数据·人工智能·python·深度学习·机器学习·语言模型·数据挖掘
AI视频工具指南18 小时前
一个人能做 AI 短剧吗?实际要做哪些决定
人工智能·aigc·音视频·1024程序员节
数聚天成DeepSData18 小时前
第三方地图工具导出的 Landsat 影像,使用条件和 USGS 官方下载的一样吗
人工智能·深度学习·机器学习·数据集·deepsdata
啥都鼓捣的小yao19 小时前
Vision Transformer(ViT)深入浅出
人工智能·深度学习·transformer