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

复制代码
import librosa
import numpy as np
import utils
import torch
import torch.nn.functional as F
from matplotlib import pyplot as plt
from torchvision.models.feature_extraction import create_feature_extractor

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 = "b093.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 为输入模型的样本特征
features = {"cnn1": '1', "cnn2": '2', "cnn3": '3', "cnn4": '4', "cnn5": '5', "cnn6": '6'}


model = torch.load(f'best_model_2.pth')
feature_extractor = create_feature_extractor(model, return_nodes=features)
out = feature_extractor(value)

layer = "3"
out = torch.cat((out[layer][0], out[layer][1]), dim=1)
out = out.unsqueeze(0)
out = F.interpolate(out, size=(470, 64), mode='bilinear', align_corners=False)
out = out.squeeze(0) .permute(2, 0, 1)   #[128, 256, 64]->[64, 128, 256]->[纵, 值, 横]
plt.imshow(out.sum(1).detach().cpu().numpy(), origin='lower')
plt.show()

参考文章:【Pytorch】六行代码实现:特征图提取与特征图可视化

相关推荐
夏天是冰红茶3 小时前
DINO原理详解
人工智能·深度学习·机器学习
吴佳浩6 小时前
Python入门指南(六) - 搭建你的第一个YOLO检测API
人工智能·后端·python
SHIPKING3936 小时前
【AI应用开发设计指南】基于163邮箱SMTP服务实现验证登录
人工智能
yong99906 小时前
基于SIFT特征提取与匹配的MATLAB图像拼接
人工智能·计算机视觉·matlab
知秋一叶1237 小时前
Miloco 深度打通 Home Assistant,实现设备级精准控制
人工智能·智能家居
春日见7 小时前
在虚拟机上面无法正启动机械臂的控制launch文件
linux·运维·服务器·人工智能·驱动开发·ubuntu
————A7 小时前
强化学习----->轨迹、回报、折扣因子和回合
人工智能·python
CareyWYR8 小时前
每周AI论文速递(251215-251219)
人工智能
weixin_409383128 小时前
在kaggle训练Qwen/Qwen2.5-1.5B-Instruct 通过中二时期qq空间记录作为训练数据 训练出中二的模型为目标 第一次训练 好像太二了
人工智能·深度学习·机器学习·qwen
JoannaJuanCV8 小时前
自动驾驶—CARLA仿真(22)manual_control_steeringwheel demo
人工智能·自动驾驶·pygame·carla