1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
| import torch import torch.nn as nn from transformers import AutoTokenizer, AutoModel import numpy as np
class TextGuidedSER(nn.Module): """ 文本引导环境感知语音情绪识别 论文: Leem et al., arXiv 2407.17716 核心: 用环境文本描述引导SER模型适应噪声 车载场景应用: - 环境描述: "汽车座舱内,引擎噪声和风噪" - SNR范围: 0-15dB(典型座舱) - 情绪维度: arousal(唤醒) / valence(效价) / dominance(支配) """ def __init__(self, speech_encoder_name='facebook/wav2vec2-base', text_encoder_name='bert-base-uncased', emotion_dim=3, hidden_dim=256): super().__init__() self.speech_encoder = AutoModel.from_pretrained(speech_encoder_name) speech_feat_dim = self.speech_encoder.config.hidden_size self.text_tokenizer = AutoTokenizer.from_pretrained(text_encoder_name) self.text_encoder = AutoModel.from_pretrained(text_encoder_name) text_feat_dim = self.text_encoder.config.hidden_size self.fusion = nn.Sequential( nn.Linear(speech_feat_dim + text_feat_dim, hidden_dim), nn.LayerNorm(hidden_dim), nn.GELU(), nn.Dropout(0.1), nn.Linear(hidden_dim, hidden_dim // 2), nn.LayerNorm(hidden_dim // 2), nn.GELU(), nn.Dropout(0.1), ) self.emotion_head = nn.Linear(hidden_dim // 2, emotion_dim) def forward(self, speech, text_input_ids, text_attention_mask): """ 前向传播 Args: speech: 语音波形, shape=(B, T) text_input_ids: 环境描述token, shape=(B, L) text_attention_mask: 文本attention mask Returns: emotions: (arousal, valence, dominance), shape=(B, 3) """ speech_outputs = self.speech_encoder(speech) speech_features = speech_outputs.last_hidden_state.mean(dim=1) text_outputs = self.text_encoder( input_ids=text_input_ids, attention_mask=text_attention_mask ) text_features = text_outputs.last_hidden_state[:, 0, :] combined = torch.cat([speech_features, text_features], dim=-1) fused = self.fusion(combined) emotions = self.emotion_head(fused) return emotions def predict_emotion(self, speech, environment_text): """ 预测情绪(推理时使用) Args: speech: 语音波形 environment_text: 环境描述,如"在汽车座舱内,引擎噪声" Returns: dict: {arousal, valence, dominance} """ tokens = self.text_tokenizer( environment_text, return_tensors='pt', padding=True, truncation=True, max_length=128 ) with torch.no_grad(): emotions = self.forward( speech.unsqueeze(0), tokens['input_ids'], tokens['attention_mask'] ) return { 'arousal': emotions[0, 0].item(), 'valence': emotions[0, 1].item(), 'dominance': emotions[0, 2].item() }
class TG_EAT_Trainer: """ 文本引导环境感知训练器 训练策略: 1. 干净语音 + 环境噪声 → 带噪语音 2. 环境文本描述 → 文本嵌入 3. 带噪语音 + 文本嵌入 → 情绪预测 4. 损失: MSE (arousal/valence/dominance) """ CABIN_NOISE_TEMPLATES = [ "Inside a car cabin with engine noise and road noise", "Inside a vehicle driving on highway with wind noise", "Inside a car with air conditioning running", "Inside an electric vehicle with minimal motor noise", "Inside a car with rain noise on the roof", "Inside a truck cabin with diesel engine noise", "Inside a car with music playing in background", "Inside a vehicle in heavy traffic with horn sounds", ] def __init__(self, model, learning_rate=1e-5): self.model = model self.optimizer = torch.optim.AdamW( model.parameters(), lr=learning_rate, weight_decay=0.01 ) self.criterion = nn.MSELoss() def add_noise(self, clean_speech, noise, snr_db): """ 添加噪声到干净语音 Args: clean_speech: 干净语音 noise: 噪声信号 snr_db: 目标信噪比(dB) """ speech_power = torch.mean(clean_speech ** 2) noise_power = torch.mean(noise ** 2) snr_linear = 10 ** (snr_db / 10) scale = torch.sqrt(speech_power / (noise_power * snr_linear + 1e-8)) noisy_speech = clean_speech + scale * noise return noisy_speech def train_step(self, clean_speech, noise, emotion_labels, env_text_ids, env_text_mask, snr_db=None): """ 单步训练 Args: clean_speech: 干净语音 (B, T) noise: 噪声信号 (B, T) emotion_labels: 情绪标签 (B, 3) [arousal, valence, dominance] env_text_ids: 环境文本token env_text_mask: 文本mask snr_db: 信噪比,随机采样 """ if snr_db is None: snr_db = np.random.choice([-5, 0, 5, 10, 15, 20]) noisy_speech = self.add_noise(clean_speech, noise, snr_db) pred_emotions = self.model(noisy_speech, env_text_ids, env_text_mask) loss = self.criterion(pred_emotions, emotion_labels) self.optimizer.zero_grad() loss.backward() torch.nn.utils.clip_grad_norm_(self.model.parameters(), 1.0) self.optimizer.step() return loss.item(), snr_db
if __name__ == "__main__": print("=== 车载语音情绪识别噪声鲁棒性测试 ===\n") model = TextGuidedSER() model.eval() np.random.seed(42) speech = torch.randn(16000 * 3) environments = [ "Inside a quiet electric vehicle cabin", "Inside a car on highway with heavy wind noise", "Inside a truck with diesel engine noise", "Inside a sports car with loud engine noise", ] print("环境描述对情绪识别的影响:\n") for env in environments: result = model.predict_emotion(speech, env) print(f"环境: {env}") print(f" Arousal: {result['arousal']:.2f} (唤醒度)") print(f" Valence: {result['valence']:.2f} (效价)") print(f" Dominance: {result['dominance']:.2f} (支配度)") print() print("=== 论文报告性能(-5dB SNR)===") print("vs 最佳基线:") print(" Arousal: +31.8%") print(" Dominance: +23.5%") print(" Valence: +9.5%") print() print("vs 原始SSL模型:") print(" Arousal: +163.6%") print(" Dominance: +200.0%") print(" Valence: +91.6%")
|