OSCR

Research on contextual sentiment recognition based on neural encoding and decoding and knowledge guidance.

Code ↔ Paper

34 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 34 matches
  1. [1] § Experimental verification and analysis › Analysis of experimental results ↔ main.py, lines 164–300 · score 0.91 · LLaMA, DialogRNN, lightweight version, 4.2 min, 4.8, 79.3 %
  2. [2] § Experimental verification and analysis › Analysis of experimental results ↔ main.py, lines 164–300 · score 0.88 · inference speed, computational efficiency, LLaMA, lightweight version, full model, SOTA
  3. [3] § Experimental verification and analysis › Experimental setup ↔ config.py, lines 328–417 · score 0.88 · EMO BART, graph attention, MultiEMO, LLaMA, DialogRNN, KGAN
  4. [4] § Experimental verification and analysis › Analysis of experimental results ↔ complete_experiment/scripts/generate_tables.py, lines 155–164 · score 0.86 · inference speed, computational efficiency, LLaMA, DialogRNN, lightweight version, GB
  5. [5] § Experimental verification and analysis › Module effectiveness and generalization verification ↔ evaluate.py, lines 167–298 · score 0.85 · knowledge guidance module, alignment loss, ablation experiments, distillation loss, macro F1, multimodal fusion
  6. [6] § Experimental verification and analysis › Analysis of experimental results ↔ complete_experiment/scripts/generate_tables.py, lines 155–164 · score 0.84 · inference speed, computational efficiency, LLaMA, lightweight version, GB, sec
  7. [7] § Contextual sentiment recognition model integrating neural encoding and decoding with knowledge guidance › Loss function design ↔ train.py, lines 128–198 · score 0.81 · modality alignment loss, loss weight, classification loss, knowledge distillation loss, cross entropy, optimized
  8. [8] § Experimental verification and analysis › Analysis of experimental results ↔ generate_data.py, lines 198–212 · score 0.79 · LLaMA, DialogRNN, lightweight version, 4.2 min, 4.8, memory
  9. [9] § Experimental verification and analysis › Module effectiveness and generalization verification ↔ generate_data.py, lines 215–251 · score 0.77 · IEMOCAP MELD, LLaMA, DialogRNN, DailyDialog, finetuned, MGAT
  10. [10] § Contextual sentiment recognition model integrating neural encoding and decoding with knowledge guidance › Loss function design ↔ train.py, lines 128–198 · score 0.75 · class weighted cross, alignment loss, distillation loss, Loss function, cosine, entropy
  11. [11] § Experimental verification and analysis › Experimental setup ↔ complete_experiment/scripts/generate_tables.py, lines 75–97 · score 0.72 · emotional shift intensity, modality missing patterns, class distribution, EDA, consecutive
  12. [12] § Contextual sentiment recognition model integrating neural encoding and decoding with knowledge guidance › Neural encoder-decoder module ↔ model.py, lines 15–65 · score 0.71 · ASPP module, global features, dilation rates
  13. [13] § Contextual sentiment recognition model integrating neural encoding and decoding with knowledge guidance › Loss function design ↔ train.py, lines 53–88 · score 0.71 · semantic space, Modality alignment loss, video features, encourages, cosine, speech
  14. [14] § Contextual sentiment recognition model integrating neural encoding and decoding with knowledge guidance › Loss function design ↔ train.py, lines 23–50 · score 0.71 · KL divergence, Knowledge distillation loss, teacher model, student, temperature, probabilities
  15. [15] § Contextual sentiment recognition model integrating neural encoding and decoding with knowledge guidance › Loss function design ↔ complete_experiment/src/data/smote_balancing.py, lines 175–206 · score 0.71 · dynamic online, random cropping, stretching, translation, audio, augmentation
  16. [16] § Contextual sentiment recognition model integrating neural encoding and decoding with knowledge guidance › Knowledge guidance mechanism ↔ model.py, lines 205–279 · score 0.71 · implicit knowledge, personality traits, domain rules, explicit knowledge guidance, concatenated, fused
  17. [17] § Contextual sentiment recognition model integrating neural encoding and decoding with knowledge guidance › Loss function design ↔ Training Pipeline .py, lines 134–173 · score 0.70 · KL divergence, Knowledge distillation loss, teacher model, student, temperature, probabilities
  18. [18] § Contextual sentiment recognition model integrating neural encoding and decoding with knowledge guidance › Overall architecture design ↔ model.py, lines 282–349 · score 0.70 · window filtering, emotional shift intensity, dynamic window, Sigmoid
  19. [19] § Experimental verification and analysis › Analysis of experimental results ↔ config.py, lines 328–417 · score 0.69 · EMO BART, MultiEMO, knowledge graphs, KGAN, fusion, weight
  20. [20] § Contextual sentiment recognition model integrating neural encoding and decoding with knowledge guidance › Knowledge guidance mechanism › Explicit knowledge fusion: ↔ model.py, lines 205–279 · score 0.68 · fused explicit knowledge, feature dimension, domain rule, linear, fusion, personality
  21. [21] § Contextual sentiment recognition model integrating neural encoding and decoding with knowledge guidance › Loss function design ↔ config.py, lines 78–149 · score 0.66 · loss weight, classification loss, modality alignment, knowledge distillation, robustness, optimized
  22. [22] § Experimental verification and analysis › Analysis of experimental results ↔ generate_data.py, lines 43–95 · score 0.66 · LLaMA, DialogRNN, DailyDialog, finetuned, MGAT, MELD
  23. [23] § Experimental verification and analysis › Experimental setup ↔ config.py, lines 10–75 · score 0.65 · facial keypoints, emotion categories, spectrograms, knowledge guidance, MFCC, BERT
  24. [24] § Experimental verification and analysis › Analysis of experimental results ↔ model.py, lines 68–134 · score 0.64 · atrous spatial pyramid, multimodal features, ASPP, fusing, fusion, speech
  25. [25] § Experimental verification and analysis › Experimental setup ↔ notebooks/01_data_exploration.ipynb, lines 143–171 · score 0.64 · modality missing, class distribution, emotional shift, EDA
  26. [26] § Experimental verification and analysis › Analysis of experimental results ↔ complete_experiment/scripts/generate_tables.py, lines 167–211 · score 0.62 · multimodal fusion, dynamic context, knowledge guidance, variant, window, distillation
  27. [27] § Experimental verification and analysis › Module effectiveness and generalization verification ↔ generate_data.py, lines 254–284 · score 0.62 · lightweight version, DailyDialog, GPT, finetuned, MELD, IEMOCAP
  28. [28] § Contextual sentiment recognition model integrating neural encoding and decoding with knowledge guidance › Loss function design ↔ complete_experiment/src/training/trainer.py, lines 341–371 · score 0.60 · cross entropy, class weighted, Loss function, cosine, training, accuracy
  29. [29] § Experimental verification and analysis › Module effectiveness and generalization verification ↔ model.py, lines 282–349 · score 0.58 · medium window, dynamic window, moderate, weight, Module, model
  30. [30] § Experimental verification and analysis › Experimental setup ↔ complete_experiment/src/data/preprocessor.py, lines 377–405 · score 0.57 · daily_dialog, Hugging Face, dialogue, speakers, video, emotional
  31. [31] § Contextual sentiment recognition model integrating neural encoding and decoding with knowledge guidance › Loss function design ↔ train.py, lines 91–121 · score 0.56 · ground truth, cross entropy loss, predict, model
  32. [32] § Contextual sentiment recognition model integrating neural encoding and decoding with knowledge guidance › Neural encoder-decoder module ↔ model.py, lines 15–65 · score 0.55 · Atrous Spatial Pyramid, parallel, ASPP, module
  33. [33] § Experimental verification and analysis › Module effectiveness and generalization verification ↔ complete_experiment/scripts/generate_tables.py, lines 13–72 · score 0.53 · fine tuned, API, GPT, frame, prompt, branches
  34. [34] § Contextual sentiment recognition model integrating neural encoding and decoding with knowledge guidance › Loss function design ↔ train.py, lines 91–121 · score 0.51 · cross entropy loss, Class weighted cross, imbalance, training, model

Paper

Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Python · 617 lines · 22 KB · no license · 7 matches

  1. """
  2. Contextual Sentiment Recognition Model
  3. Based on: "Research on Contextual Sentiment Recognition Based on Neural Encoding and Decoding and Knowledge Guidance"
  4. This module implements the dual-branch neural encoding-decoding architecture with dynamic knowledge guidance.
  5. """
  6. import torch
  7. import torch.nn as nn
  8. import torch.nn.functional as F
  9. import math
  10. from typing import Optional, Tuple, Dict, List
  11. class AtrousSpatialPyramidPooling(nn.Module):
  12. """
  13. ASPP module for multi-scale feature extraction.
  14. Uses dilation rates {1, 3, 6, 12} as specified in the paper.
  15. """
  16. def __init__(self, in_channels: int, out_channels: int = 512):
  17. super().__init__()
  18. self.dilation_rates = [1, 3, 6, 12]
  19. # Parallel dilated convolutions
  20. self.convs = nn.ModuleList([
  21. nn.Conv1d(in_channels, out_channels // 4, kernel_size=3,
  22. padding=rate, dilation=rate)
  23. for rate in self.dilation_rates
  24. ])
  25. # Global feature pooling
  26. self.global_pool = nn.AdaptiveAvgPool1d(1)
  27. self.global_conv = nn.Conv1d(in_channels, out_channels // 4, kernel_size=1)
  28. # Fusion convolution
  29. self.fusion_conv = nn.Conv1d(out_channels, out_channels, kernel_size=1)
  30. self.bn = nn.BatchNorm1d(out_channels)
  31. def forward(self, x: torch.Tensor) -> torch.Tensor:
  32. """
  33. Args:
  34. x: Input tensor of shape (batch, in_channels, seq_len)
  35. Returns:
  36. Output tensor of shape (batch, out_channels, seq_len)
  37. """
  38. # Extract multi-scale features
  39. multi_scale_features = []
  40. for conv in self.convs:
  41. multi_scale_features.append(conv(x))
  42. # Global feature
  43. global_feat = self.global_pool(x)
  44. global_feat = self.global_conv(global_feat)
  45. global_feat = F.interpolate(global_feat, size=x.size(-1), mode='linear', align_corners=False)
  46. multi_scale_features.append(global_feat)
  47. # Concatenate all features
  48. fused = torch.cat(multi_scale_features, dim=1)
  49. # Fusion
  50. output = self.fusion_conv(fused)
  51. output = self.bn(output)
  52. output = F.relu(output)
  53. return output
  54. class MultimodalFeatureEncoder(nn.Module):
  55. """
  56. Multimodal feature encoder that processes text, speech, and video features.
  57. Implements Equation (7) from the paper.
  58. """
  59. def __init__(self,
  60. text_dim: int = 768,
  61. speech_dim: int = 512,
  62. video_dim: int = 256,
  63. hidden_dim: int = 1536):
  64. super().__init__()
  65. self.text_dim = text_dim
  66. self.speech_dim = speech_dim
  67. self.video_dim = video_dim
  68. self.hidden_dim = hidden_dim
  69. # Text feature projection
  70. self.text_proj = nn.Linear(text_dim, hidden_dim // 3)
  71. # Speech feature projection with ASPP
  72. self.speech_aspp = AtrousSpatialPyramidPooling(speech_dim, hidden_dim // 3)
  73. self.speech_proj = nn.Linear(hidden_dim // 3, hidden_dim // 3)
  74. # Video feature projection with ASPP
  75. self.video_aspp = AtrousSpatialPyramidPooling(video_dim, hidden_dim // 3)
  76. self.video_proj = nn.Linear(hidden_dim // 3, hidden_dim // 3)
  77. # Feature fusion
  78. self.fusion_layer = nn.Sequential(
  79. nn.Linear(hidden_dim, hidden_dim),
  80. nn.LayerNorm(hidden_dim),
  81. nn.ReLU(),
  82. nn.Dropout(0.1)
  83. )
  84. def forward(self,
  85. text_feat: torch.Tensor,
  86. speech_feat: torch.Tensor,
  87. video_feat: torch.Tensor) -> torch.Tensor:
  88. """
  89. Args:
  90. text_feat: (batch, text_dim)
  91. speech_feat: (batch, speech_dim, seq_len)
  92. video_feat: (batch, video_dim, seq_len)
  93. Returns:
  94. Fused multimodal feature (batch, hidden_dim)
  95. """
  96. # Process text features
  97. text_out = self.text_proj(text_feat) # (batch, hidden_dim//3)
  98. # Process speech features with ASPP
  99. speech_out = self.speech_aspp(speech_feat) # (batch, hidden_dim//3, seq_len)
  100. speech_out = F.adaptive_avg_pool1d(speech_out, 1).squeeze(-1) # (batch, hidden_dim//3)
  101. speech_out = self.speech_proj(speech_out)
  102. # Process video features with ASPP
  103. video_out = self.video_aspp(video_feat) # (batch, hidden_dim//3, seq_len)
  104. video_out = F.adaptive_avg_pool1d(video_out, 1).squeeze(-1) # (batch, hidden_dim//3)
  105. video_out = self.video_proj(video_out)
  106. # Concatenate all features (Equation 7)
  107. fused = torch.cat([text_out, speech_out, video_out], dim=-1) # (batch, hidden_dim)
  108. # Apply fusion layer
  109. output = self.fusion_layer(fused)
  110. return output
  111. class ContextualEncoder(nn.Module):
  112. """
  113. Contextual feature encoder using Transformer.
  114. Implements Equation (8) from the paper.
  115. """
  116. def __init__(self,
  117. input_dim: int = 1536,
  118. hidden_dim: int = 512,
  119. num_layers: int = 3,
  120. num_heads: int = 8,
  121. dropout: float = 0.1):
  122. super().__init__()
  123. self.input_proj = nn.Linear(input_dim, hidden_dim)
  124. # Positional encoding
  125. self.pos_encoding = PositionalEncoding(hidden_dim, dropout)
  126. # Transformer encoder layers
  127. encoder_layer = nn.TransformerEncoderLayer(
  128. d_model=hidden_dim,
  129. nhead=num_heads,
  130. dim_feedforward=hidden_dim * 4,
  131. dropout=dropout,
  132. activation='gelu',
  133. batch_first=True
  134. )
  135. self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
  136. def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:
  137. """
  138. Args:
  139. x: Input sequence (batch, seq_len, input_dim)
  140. mask: Optional attention mask
  141. Returns:
  142. Contextual features (batch, seq_len, hidden_dim)
  143. """
  144. # Project input
  145. x = self.input_proj(x)
  146. # Add positional encoding
  147. x = self.pos_encoding(x)
  148. # Apply transformer
  149. output = self.transformer(x, src_key_padding_mask=mask)
  150. return output
  151. class PositionalEncoding(nn.Module):
  152. """Positional encoding for transformer."""
  153. def __init__(self, d_model: int, dropout: float = 0.1, max_len: int = 5000):
  154. super().__init__()
  155. self.dropout = nn.Dropout(p=dropout)
  156. pe = torch.zeros(max_len, d_model)
  157. position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
  158. div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
  159. pe[:, 0::2] = torch.sin(position * div_term)
  160. pe[:, 1::2] = torch.cos(position * div_term)
  161. pe = pe.unsqueeze(0)
  162. self.register_buffer('pe', pe)
  163. def forward(self, x: torch.Tensor) -> torch.Tensor:
  164. x = x + self.pe[:, :x.size(1), :]
  165. return self.dropout(x)
  166. class KnowledgeGuidance(nn.Module):
  167. """
  168. Knowledge guidance mechanism integrating explicit and implicit knowledge.
  169. Implements Equations (9), (14), (15), (18), (19), (20) from the paper.
  170. """
  171. def __init__(self,
  172. personality_dim: int = 5,
  173. rule_vocab_size: int = 100,
  174. embed_dim: int = 256,
  175. feature_dim: int = 512,
  176. num_heads: int = 8):
  177. super().__init__()
  178. # Personality trait encoding (Equation 18)
  179. self.personality_encoder = nn.Sequential(
  180. nn.Linear(personality_dim, embed_dim),
  181. nn.ReLU(),
  182. nn.Linear(embed_dim, embed_dim)
  183. )
  184. # Domain rule embedding (Equation 19)
  185. self.rule_embedding = nn.Embedding(rule_vocab_size, embed_dim)
  186. # Explicit knowledge fusion (Equation 20)
  187. self.alpha = 0.6 # Weight for personality
  188. self.beta = 0.4 # Weight for domain rules
  189. # Knowledge-guided attention (Equation 14)
  190. self.knowledge_attention = nn.MultiheadAttention(
  191. embed_dim=feature_dim,
  192. num_heads=num_heads,
  193. batch_first=True
  194. )
  195. # Project knowledge to feature dimension
  196. self.knowledge_proj = nn.Linear(embed_dim * 2, feature_dim)
  197. def forward(self,
  198. features: torch.Tensor,
  199. personality: torch.Tensor,
  200. rule_ids: torch.Tensor) -> torch.Tensor:
  201. """
  202. Args:
  203. features: Feature tensor (batch, seq_len, feature_dim)
  204. personality: Personality traits (batch, 5) - Big Five
  205. rule_ids: Domain rule indices (batch,)
  206. Returns:
  207. Knowledge-weighted features (batch, seq_len, feature_dim)
  208. """
  209. # Encode personality traits
  210. K_p = self.personality_encoder(personality) # (batch, embed_dim)
  211. # Encode domain rules
  212. K_r = self.rule_embedding(rule_ids) # (batch, embed_dim)
  213. # Fuse explicit knowledge (Equation 20)
  214. K_explicit = self.alpha * K_p + self.beta * K_r # (batch, embed_dim)
  215. # Concatenate with implicit knowledge placeholder
  216. # In practice, implicit knowledge would be distilled from LLM
  217. K_implicit = torch.zeros_like(K_explicit)
  218. K = torch.cat([K_explicit, K_implicit], dim=-1) # (batch, embed_dim * 2)
  219. # Project knowledge to feature dimension
  220. K_proj = self.knowledge_proj(K).unsqueeze(1) # (batch, 1, feature_dim)
  221. # Knowledge-guided attention (Equation 14)
  222. attn_output, _ = self.knowledge_attention(
  223. K_proj, features, features
  224. )
  225. # Combine with original features
  226. output = features + attn_output.expand(-1, features.size(1), -1)
  227. return output
  228. class DynamicContextWindow(nn.Module):
  229. """
  230. Dynamic context window that adapts based on emotional shift intensity.
  231. Implements Equation (10) from the paper.
  232. """
  233. def __init__(self,
  234. min_window: int = 3,
  235. max_window: int = 10,
  236. shift_threshold_high: float = 0.6,
  237. shift_threshold_low: float = 0.2):
  238. super().__init__()
  239. self.min_window = min_window
  240. self.max_window = max_window
  241. self.shift_threshold_high = shift_threshold_high
  242. self.shift_threshold_low = shift_threshold_low
  243. def compute_window_size(self, emotional_shift: torch.Tensor) -> int:
  244. """
  245. Compute dynamic window size based on emotional shift intensity.
  246. Args:
  247. emotional_shift: Emotional shift intensity (batch,)
  248. Returns:
  249. Window size (int)
  250. """
  251. # Apply thresholds as specified in paper
  252. if emotional_shift.mean() > self.shift_threshold_high:
  253. return self.min_window # W=3 for rapid changes
  254. elif emotional_shift.mean() < self.shift_threshold_low:
  255. return self.max_window # W=10 for stable periods
  256. else:
  257. return 5 # Medium window for moderate shifts
  258. def forward(self,
  259. features: torch.Tensor,
  260. emotional_shifts: torch.Tensor) -> torch.Tensor:
  261. """
  262. Apply dynamic window filtering.
  263. Args:
  264. features: Feature sequence (batch, seq_len, feature_dim)
  265. emotional_shifts: Emotional shift intensities (batch, seq_len)
  266. Returns:
  267. Window-filtered features (batch, feature_dim)
  268. """
  269. batch_size, seq_len, feature_dim = features.shape
  270. # Compute window size for each sample
  271. window_sizes = []
  272. for i in range(batch_size):
  273. w = self.compute_window_size(emotional_shifts[i])
  274. window_sizes.append(w)
  275. # Apply window filtering with sigmoid weighting
  276. outputs = []
  277. for i in range(batch_size):
  278. w = min(window_sizes[i], seq_len)
  279. window_feats = features[i, -w:, :] # Take last w features
  280. # Compute sigmoid weights based on emotional shifts
  281. shifts = emotional_shifts[i, -w:]
  282. weights = torch.sigmoid(shifts).unsqueeze(-1) # (w, 1)
  283. # Weighted aggregation
  284. weighted_feat = (window_feats * weights).sum(dim=0) / (weights.sum() + 1e-8)
  285. outputs.append(weighted_feat)
  286. return torch.stack(outputs)
  287. class ContextualSentimentModel(nn.Module):
  288. """
  289. Complete contextual sentiment recognition model.
  290. Integrates all components: multimodal encoder, contextual encoder,
  291. knowledge guidance, and dynamic context window.
  292. """
  293. def __init__(self,
  294. num_emotions: int = 7,
  295. text_dim: int = 768,
  296. speech_dim: int = 512,
  297. video_dim: int = 256,
  298. hidden_dim: int = 1536,
  299. context_dim: int = 512,
  300. num_context_layers: int = 3,
  301. num_heads: int = 8,
  302. dropout: float = 0.1):
  303. super().__init__()
  304. self.num_emotions = num_emotions
  305. # Multimodal feature encoder
  306. self.multimodal_encoder = MultimodalFeatureEncoder(
  307. text_dim=text_dim,
  308. speech_dim=speech_dim,
  309. video_dim=video_dim,
  310. hidden_dim=hidden_dim
  311. )
  312. # Contextual encoder
  313. self.contextual_encoder = ContextualEncoder(
  314. input_dim=hidden_dim,
  315. hidden_dim=context_dim,
  316. num_layers=num_context_layers,
  317. num_heads=num_heads,
  318. dropout=dropout
  319. )
  320. # Knowledge guidance
  321. self.knowledge_guidance = KnowledgeGuidance(
  322. feature_dim=context_dim
  323. )
  324. # Dynamic context window
  325. self.dynamic_window = DynamicContextWindow()
  326. # Feature fusion (Equation 9)
  327. self.fusion_alpha = 0.4 # Multimodal weight
  328. self.fusion_beta = 0.3 # Contextual weight
  329. self.fusion_gamma = 0.3 # Knowledge weight
  330. # Fusion projection
  331. self.fusion_proj = nn.Sequential(
  332. nn.Linear(hidden_dim + context_dim * 2, hidden_dim),
  333. nn.LayerNorm(hidden_dim),
  334. nn.ReLU(),
  335. nn.Dropout(dropout)
  336. )
  337. # Classification head
  338. self.classifier = nn.Sequential(
  339. nn.Linear(hidden_dim, hidden_dim // 2),
  340. nn.ReLU(),
  341. nn.Dropout(dropout),
  342. nn.Linear(hidden_dim // 2, num_emotions)
  343. )
  344. # Emotional shift predictor for dynamic window
  345. self.shift_predictor = nn.Linear(context_dim, 1)
  346. def forward(self,
  347. text: torch.Tensor,
  348. speech: torch.Tensor,
  349. video: torch.Tensor,
  350. personality: torch.Tensor,
  351. rule_ids: torch.Tensor,
  352. context_mask: Optional[torch.Tensor] = None) -> Dict[str, torch.Tensor]:
  353. """
  354. Forward pass of the model.
  355. Args:
  356. text: Text features (batch, seq_len, text_dim)
  357. speech: Speech features (batch, seq_len, speech_dim, seq_len2)
  358. video: Video features (batch, seq_len, video_dim, seq_len2)
  359. personality: Personality traits (batch, 5)
  360. rule_ids: Domain rule indices (batch,)
  361. context_mask: Optional mask for context (batch, seq_len)
  362. Returns:
  363. Dictionary containing logits, emotional shifts, and intermediate features
  364. """
  365. batch_size, seq_len = text.shape[:2]
  366. # Encode multimodal features for each turn
  367. multimodal_feats = []
  368. for t in range(seq_len):
  369. # Extract features for turn t
  370. text_t = text[:, t, :] # (batch, text_dim)
  371. speech_t = speech[:, t, :, :] # (batch, speech_dim, seq_len2)
  372. video_t = video[:, t, :, :] # (batch, video_dim, seq_len2)
  373. # Encode multimodal features
  374. mm_feat = self.multimodal_encoder(text_t, speech_t, video_t)
  375. multimodal_feats.append(mm_feat)
  376. multimodal_feats = torch.stack(multimodal_feats, dim=1) # (batch, seq_len, hidden_dim)
  377. # Encode contextual features
  378. context_feats = self.contextual_encoder(multimodal_feats, mask=context_mask)
  379. # (batch, seq_len, context_dim)
  380. # Apply knowledge guidance
  381. knowledge_feats = self.knowledge_guidance(context_feats, personality, rule_ids)
  382. # (batch, seq_len, context_dim)
  383. # Predict emotional shifts for dynamic window
  384. emotional_shifts = self.shift_predictor(knowledge_feats).squeeze(-1)
  385. # (batch, seq_len)
  386. emotional_shifts = torch.sigmoid(emotional_shifts)
  387. # Apply dynamic context window
  388. windowed_feats = self.dynamic_window(knowledge_feats, emotional_shifts)
  389. # (batch, context_dim)
  390. # Get last multimodal feature
  391. last_mm_feat = multimodal_feats[:, -1, :] # (batch, hidden_dim)
  392. # Get last contextual feature
  393. last_ctx_feat = context_feats[:, -1, :] # (batch, context_dim)
  394. # Feature fusion (Equation 9)
  395. fused = torch.cat([last_mm_feat, last_ctx_feat, windowed_feats], dim=-1)
  396. fused = self.fusion_proj(fused)
  397. # Classification
  398. logits = self.classifier(fused)
  399. return {
  400. 'logits': logits,
  401. 'emotional_shifts': emotional_shifts,
  402. 'multimodal_feats': multimodal_feats,
  403. 'context_feats': context_feats,
  404. 'fused_feats': fused
  405. }
  406. class LightweightContextualSentimentModel(nn.Module):
  407. """
  408. Lightweight version of the model with reduced parameters.
  409. 18.2M parameters vs 36.8M in full version.
  410. """
  411. def __init__(self,
  412. num_emotions: int = 7,
  413. text_dim: int = 768,
  414. speech_dim: int = 512,
  415. video_dim: int = 256,
  416. hidden_dim: int = 768,
  417. context_dim: int = 256,
  418. num_context_layers: int = 2,
  419. num_heads: int = 4,
  420. dropout: float = 0.1):
  421. super().__init__()
  422. # Simplified multimodal encoder
  423. self.text_proj = nn.Linear(text_dim, hidden_dim // 3)
  424. self.speech_proj = nn.Linear(speech_dim, hidden_dim // 3)
  425. self.video_proj = nn.Linear(video_dim, hidden_dim // 3)
  426. # Simplified contextual encoder
  427. self.context_encoder = nn.LSTM(
  428. input_size=hidden_dim,
  429. hidden_size=context_dim,
  430. num_layers=2,
  431. batch_first=True,
  432. dropout=dropout,
  433. bidirectional=True
  434. )
  435. # Simplified classifier
  436. self.classifier = nn.Sequential(
  437. nn.Linear(hidden_dim + context_dim * 2, hidden_dim // 2),
  438. nn.ReLU(),
  439. nn.Dropout(dropout),
  440. nn.Linear(hidden_dim // 2, num_emotions)
  441. )
  442. def forward(self,
  443. text: torch.Tensor,
  444. speech: torch.Tensor,
  445. video: torch.Tensor,
  446. personality: Optional[torch.Tensor] = None,
  447. rule_ids: Optional[torch.Tensor] = None,
  448. context_mask: Optional[torch.Tensor] = None) -> Dict[str, torch.Tensor]:
  449. """
  450. Simplified forward pass for lightweight model.
  451. """
  452. batch_size, seq_len = text.shape[:2]
  453. # Simple multimodal fusion
  454. multimodal_feats = []
  455. for t in range(seq_len):
  456. text_t = self.text_proj(text[:, t, :])
  457. speech_t = self.speech_proj(speech[:, t, :, :].mean(dim=-1))
  458. video_t = self.video_proj(video[:, t, :, :].mean(dim=-1))
  459. fused = torch.cat([text_t, speech_t, video_t], dim=-1)
  460. multimodal_feats.append(fused)
  461. multimodal_feats = torch.stack(multimodal_feats, dim=1)
  462. # LSTM contextual encoding
  463. context_feats, _ = self.context_encoder(multimodal_feats)
  464. # Classification
  465. combined = torch.cat([
  466. multimodal_feats[:, -1, :],
  467. context_feats[:, -1, :]
  468. ], dim=-1)
  469. logits = self.classifier(combined)
  470. return {
  471. 'logits': logits,
  472. 'emotional_shifts': torch.zeros(batch_size, seq_len),
  473. 'multimodal_feats': multimodal_feats,
  474. 'context_feats': context_feats,
  475. 'fused_feats': combined
  476. }
  477. def count_parameters(model: nn.Module) -> int:
  478. """Count the number of trainable parameters in a model."""
  479. return sum(p.numel() for p in model.parameters() if p.requires_grad)
  480. if __name__ == "__main__":
  481. # Test the model
  482. print("Testing Contextual Sentiment Model...")
  483. # Create model
  484. model = ContextualSentimentModel(num_emotions=7)
  485. # Count parameters
  486. num_params = count_parameters(model)
  487. print(f"Full model parameters: {num_params / 1e6:.1f}M")
  488. # Test forward pass
  489. batch_size = 4
  490. seq_len = 10
  491. text = torch.randn(batch_size, seq_len, 768)
  492. speech = torch.randn(batch_size, seq_len, 512, 50)
  493. video = torch.randn(batch_size, seq_len, 256, 50)
  494. personality = torch.randn(batch_size, 5)
  495. rule_ids = torch.randint(0, 100, (batch_size,))
  496. output = model(text, speech, video, personality, rule_ids)
  497. print(f"Logits shape: {output['logits'].shape}")
  498. print(f"Emotional shifts shape: {output['emotional_shifts'].shape}")
  499. # Test lightweight model
  500. light_model = LightweightContextualSentimentModel(num_emotions=7)
  501. light_params = count_parameters(light_model)
  502. print(f"\nLightweight model parameters: {light_params / 1e6:.1f}M")
  503. light_output = light_model(text, speech, video)
  504. print(f"Lightweight logits shape: {light_output['logits'].shape}")

model.py, no license · at the source

Overview

Authors: Xiangyu Cheng1
  1. Department of Industrial Engineering and Operations Research, University of California,Berkeley, CA 94720 USA
Institutions: University of California, Berkeley (United States)
Journal: Scientific reports, volume 16, issue 1, article 22104
Dates: received 28 January 2026; accepted 6 May 2026; published online 14 May 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1038/s41598-026-52490-y · PMID 42135370 · PMCID PMC13369197 · OpenAlex W7161163868
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: human (organism)
Methods: Connectivity, Statistics, Machine learning, Spectral & time-frequency, Smoothing, state filtering, decompositions
Keywords: Information systems and information technology, Mathematics and computing
MeSH: Emotions*, Neural Networks, Computer*, Algorithms, Humans, Large Language Models (* major topic)
Topic: Sentiment Analysis and Opinion Mining (Artificial Intelligence, Computer Science), according to OpenAlex
Citations: not cited yet (Europe PMC); 50 references in the paper

Abstract

Contextual sentiment recognition is critical for applications such as intelligent customer service and mental health monitoring. However, existing models struggle with multimodal heterogeneity, knowledge scarcity, and inadequate capture of dynamic emotional transitions. To address these challenges, we propose a dual-branch neural encoding–decoding architecture integrated with dynamic knowledge guidance. The model processes multimodal features (text, speech, video) and contextual dependencies through separate branches, incorporating both explicit knowledge (personality traits, domain rules) and implicit knowledge distilled from large language models. A dynamic context window adapts based on emotional shifts to enhance real-time perception. Experiments on IEMOCAP, MELD, and DailyDialog datasets demonstrate that our full model achieves accuracies of 82.1%, 78.3%, and 76.2%, respectively, surpassing state-of-the-art benchmarks including fine-tuned GPT-4. The lightweight version (18.2 M parameters) maintains high inference speed (950 samples/sec) while reducing deployment costs. Furthermore, the model exhibits strong cross-dataset generalization and practical utility. This work provides an efficient framework that effectively addresses core challenges in contextual sentiment recognition, balancing performance with practicality for real-world deployment.

Reproduced under the paper's license (CC BY), from the paper cited above.

Repository

Its files are read in the Code ↔ Paper reader above, with 34 matches between paragraphs and lines of code.

OSF 5nxzq

License: none: the authors keep all their rights
State: the link answers, verified on 28 September 2026
Evidence: files inventoried
Languages: Python (17), Jupyter (2), Shell (2)
Size: 47 files, 21 scripts
Software Heritage: not checked
Found in: “Data availability”
Holds: README, environment (requirements.txt), 2 notebooks
Not found: license file, CITATION.cff, tests, continuous integration, documentation
Tools: NumPy (17 files), PyTorch (11 files), pandas (10 files), Matplotlib (6 files), scikit-learn (6 files), seaborn (6 files), Hugging Face Transformers (3 files), OpenCV (2 files), SciPy (2 files)
Availability: 1 check, the latest on 28 September 2026: the link answers (HTTP 200)
  • 28 September 2026: the link answers (HTTP 200)
22 files
At the source: osf.io/5nxzq/overview

The paper's code and data availability statement is in the Data section.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 1 repository of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 21 scripts, each with its path and the digest of its content;
  • 34 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

Datasets cited

Data availability

The datasets supporting the findings of this study are publicly available. The IEMOCAP dataset is accessible from its official website (https://sail.usc.edu/iemocap/) under a license agreement. The MELD and DailyDialog datasets can be loaded directly via the Hugging Face Datasets library at https://huggingface.co/datasets/zrr1999/MELD_Text and https://huggingface.co/datasets/li2017dailydialog/daily_dialog, respectively. All data required to interpret, verify, and extend the research in this article are available without undue qualifications. Data and code are available via the following link: https://osf.io/5nxzq/overview

Data and code are available via the following link: https://osf.io/5nxzq/overview

Reproduced under the paper's license (CC BY), from the paper cited above.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 1, 28 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 1 author, 2 keywords, 5 MeSH terms, 41 references.

Cite

This paper

Cheng, X. (2026). Research on contextual sentiment recognition based on neural encoding and decoding and knowledge guidance. Scientific reports, 16(1), 22104. https://doi.org/10.1038/s41598-026-52490-y

BibTeX

@article{cheng2026research,
author = {Cheng, Xiangyu},
title = {{Research on contextual sentiment recognition based on neural encoding and decoding and knowledge guidance}},
journal = {Scientific reports},
year = {2026},
month = may,
volume = {16},
number = {1},
pages = {22104},
publisher = {Nature Publishing Group},
issn = {2045-2322},
doi = {10.1038/s41598-026-52490-y},
url = {https://doi.org/10.1038/s41598-026-52490-y},
pmid = {42135370},
pmcid = {PMC13369197}
}

RIS

TY - JOUR
AU - Cheng, Xiangyu
TI - Research on contextual sentiment recognition based on neural encoding and decoding and knowledge guidance
T2 - Scientific reports
J2 - Sci Rep
PY - 2026
DA - 2026/05/14
VL - 16
IS - 1
SP - 22104
SN - 2045-2322
PB - Nature Publishing Group
DO - 10.1038/s41598-026-52490-y
UR - https://doi.org/10.1038/s41598-026-52490-y
LA - en
ER -

CSL-JSON

{
"id": "10.1038/s41598-026-52490-y",
"type": "article-journal",
"title": "Research on contextual sentiment recognition based on neural encoding and decoding and knowledge guidance",
"container-title": "Scientific reports",
"author": [
{
"family": "Cheng",
"given": "Xiangyu"
}
],
"container-title-short": "Sci Rep",
"volume": "16",
"issue": "1",
"page": "22104",
"DOI": "10.1038/s41598-026-52490-y",
"PMID": "42135370",
"PMCID": "PMC13369197",
"ISSN": "2045-2322",
"publisher": "Nature Publishing Group",
"URL": "https://doi.org/10.1038/s41598-026-52490-y",
"language": "en",
"issued": {
"date-parts": [
[
2026,
5,
14
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.1038/s42003-026-10957-8 [code]
Brain defence by the extracellular matrix protein Cochlin.
Journal: Communications biology
In common: Hugging Face Transformers, OpenCV, PyTorch, 6 other tools
[2] doi:10.1038/s41467-026-76837-1 [code]
Drug screen and machine learning predict neuroprotective agents in a preclinical human model of childhood dementia.
Journal: Nature communications
In common: Hugging Face Transformers, OpenCV, PyTorch, 6 other tools
[3] doi:10.1093/braincomms/fcag253 [code]
Disease detection and classification in temporal lobe epilepsy: step-wise versus simultaneous AI decision models in a multisite neuroimaging study.
Journal: Brain communications
In common: Hugging Face Transformers, OpenCV, PyTorch, 6 other tools
[4] doi:10.1038/s41467-026-74358-5 [code]
Brain-inspired spatial intelligence for embodied agents.
Journal: Nature communications
In common: Hugging Face Transformers, OpenCV, PyTorch, 6 other tools
[5] doi:10.1038/s43856-026-01606-6 [code]
Validation of remote multimodal AI screening for Parkinson disease across diverse settings.
Journal: Communications medicine
In common: Hugging Face Transformers, OpenCV, PyTorch, 6 other tools
[6] doi:10.7554/elife.107933 [code]
Modality-agnostic decoding of vision and language from fMRI.
Journal: eLife
In common: Hugging Face Transformers, OpenCV, PyTorch, 6 other tools
[7] doi:10.1002/hbm.70469 [code]
VarCoNet: A Variability-Aware Self-Supervised Framework for Functional Connectome Extraction From Resting-State fMRI.
Journal: Human brain mapping
In common: Hugging Face Transformers, OpenCV, PyTorch, 6 other tools
[8] doi:10.1038/s43856-026-01817-x [code]
Visual prompt engineering for multimodal and irregularly sampled medical data.
Journal: Communications medicine
In common: Hugging Face Transformers, OpenCV, PyTorch, 6 other tools
[9] doi:10.1038/s41598-026-50791-w [code]
Hybrid Vi+ECNN framework for advanced ADHD diagnostic accuracy in medical imaging.
Journal: Scientific reports
In common: Hugging Face Transformers, OpenCV, PyTorch, 5 other tools
[10] doi:10.1371/journal.pcbi.1014263 [code]
MIRAGE: Robust multi-modal architectures translate fMRI-to-image models from vision to mental imagery.
Journal: PLoS computational biology
In common: Hugging Face Transformers, OpenCV, PyTorch, 5 other tools

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.

Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.