Research on contextual sentiment recognition based on neural encoding and decoding and knowledge guidance.
The 34 matches
- [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] § 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] § Experimental verification and analysis › Experimental setup ↔ config.py, lines 328–417 · score 0.88 · EMO BART, graph attention, MultiEMO, LLaMA, DialogRNN, KGAN
- [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] § 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] § 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] § 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] § 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] § 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] § 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] § 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] § 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] § 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] § 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] § 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] § 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] § 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] § 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] § 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] § 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] § 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] § Experimental verification and analysis › Analysis of experimental results ↔ generate_data.py, lines 43–95 · score 0.66 · LLaMA, DialogRNN, DailyDialog, finetuned, MGAT, MELD
- [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] § 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] § 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] § 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] § 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] § 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] § 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] § 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] § 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] § 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] § 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] § 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
- """
- Contextual Sentiment Recognition Model
- Based on: "Research on Contextual Sentiment Recognition Based on Neural Encoding and Decoding and Knowledge Guidance"
- This module implements the dual-branch neural encoding-decoding architecture with dynamic knowledge guidance.
- """
- import torch
- import torch.nn as nn
- import torch.nn.functional as F
- import math
- from typing import Optional, Tuple, Dict, List
- class AtrousSpatialPyramidPooling(nn.Module):
- """
- ASPP module for multi-scale feature extraction.
- Uses dilation rates {1, 3, 6, 12} as specified in the paper.
- """
- def __init__(self, in_channels: int, out_channels: int = 512):
- super().__init__()
- self.dilation_rates = [1, 3, 6, 12]
- # Parallel dilated convolutions
- self.convs = nn.ModuleList([
- nn.Conv1d(in_channels, out_channels // 4, kernel_size=3,
- padding=rate, dilation=rate)
- for rate in self.dilation_rates
- ])
- # Global feature pooling
- self.global_pool = nn.AdaptiveAvgPool1d(1)
- self.global_conv = nn.Conv1d(in_channels, out_channels // 4, kernel_size=1)
- # Fusion convolution
- self.fusion_conv = nn.Conv1d(out_channels, out_channels, kernel_size=1)
- self.bn = nn.BatchNorm1d(out_channels)
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- """
- Args:
- x: Input tensor of shape (batch, in_channels, seq_len)
- Returns:
- Output tensor of shape (batch, out_channels, seq_len)
- """
- # Extract multi-scale features
- multi_scale_features = []
- for conv in self.convs:
- multi_scale_features.append(conv(x))
- # Global feature
- global_feat = self.global_pool(x)
- global_feat = self.global_conv(global_feat)
- global_feat = F.interpolate(global_feat, size=x.size(-1), mode='linear', align_corners=False)
- multi_scale_features.append(global_feat)
- # Concatenate all features
- fused = torch.cat(multi_scale_features, dim=1)
- # Fusion
- output = self.fusion_conv(fused)
- output = self.bn(output)
- output = F.relu(output)
- return output
- class MultimodalFeatureEncoder(nn.Module):
- """
- Multimodal feature encoder that processes text, speech, and video features.
- Implements Equation (7) from the paper.
- """
- def __init__(self,
- text_dim: int = 768,
- speech_dim: int = 512,
- video_dim: int = 256,
- hidden_dim: int = 1536):
- super().__init__()
- self.text_dim = text_dim
- self.speech_dim = speech_dim
- self.video_dim = video_dim
- self.hidden_dim = hidden_dim
- # Text feature projection
- self.text_proj = nn.Linear(text_dim, hidden_dim // 3)
- # Speech feature projection with ASPP
- self.speech_aspp = AtrousSpatialPyramidPooling(speech_dim, hidden_dim // 3)
- self.speech_proj = nn.Linear(hidden_dim // 3, hidden_dim // 3)
- # Video feature projection with ASPP
- self.video_aspp = AtrousSpatialPyramidPooling(video_dim, hidden_dim // 3)
- self.video_proj = nn.Linear(hidden_dim // 3, hidden_dim // 3)
- # Feature fusion
- self.fusion_layer = nn.Sequential(
- nn.Linear(hidden_dim, hidden_dim),
- nn.LayerNorm(hidden_dim),
- nn.ReLU(),
- nn.Dropout(0.1)
- )
- def forward(self,
- text_feat: torch.Tensor,
- speech_feat: torch.Tensor,
- video_feat: torch.Tensor) -> torch.Tensor:
- """
- Args:
- text_feat: (batch, text_dim)
- speech_feat: (batch, speech_dim, seq_len)
- video_feat: (batch, video_dim, seq_len)
- Returns:
- Fused multimodal feature (batch, hidden_dim)
- """
- # Process text features
- text_out = self.text_proj(text_feat) # (batch, hidden_dim//3)
- # Process speech features with ASPP
- speech_out = self.speech_aspp(speech_feat) # (batch, hidden_dim//3, seq_len)
- speech_out = F.adaptive_avg_pool1d(speech_out, 1).squeeze(-1) # (batch, hidden_dim//3)
- speech_out = self.speech_proj(speech_out)
- # Process video features with ASPP
- video_out = self.video_aspp(video_feat) # (batch, hidden_dim//3, seq_len)
- video_out = F.adaptive_avg_pool1d(video_out, 1).squeeze(-1) # (batch, hidden_dim//3)
- video_out = self.video_proj(video_out)
- # Concatenate all features (Equation 7)
- fused = torch.cat([text_out, speech_out, video_out], dim=-1) # (batch, hidden_dim)
- # Apply fusion layer
- output = self.fusion_layer(fused)
- return output
- class ContextualEncoder(nn.Module):
- """
- Contextual feature encoder using Transformer.
- Implements Equation (8) from the paper.
- """
- def __init__(self,
- input_dim: int = 1536,
- hidden_dim: int = 512,
- num_layers: int = 3,
- num_heads: int = 8,
- dropout: float = 0.1):
- super().__init__()
- self.input_proj = nn.Linear(input_dim, hidden_dim)
- # Positional encoding
- self.pos_encoding = PositionalEncoding(hidden_dim, dropout)
- # Transformer encoder layers
- encoder_layer = nn.TransformerEncoderLayer(
- d_model=hidden_dim,
- nhead=num_heads,
- dim_feedforward=hidden_dim * 4,
- dropout=dropout,
- activation='gelu',
- batch_first=True
- )
- self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
- def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:
- """
- Args:
- x: Input sequence (batch, seq_len, input_dim)
- mask: Optional attention mask
- Returns:
- Contextual features (batch, seq_len, hidden_dim)
- """
- # Project input
- x = self.input_proj(x)
- # Add positional encoding
- x = self.pos_encoding(x)
- # Apply transformer
- output = self.transformer(x, src_key_padding_mask=mask)
- return output
- class PositionalEncoding(nn.Module):
- """Positional encoding for transformer."""
- def __init__(self, d_model: int, dropout: float = 0.1, max_len: int = 5000):
- super().__init__()
- self.dropout = nn.Dropout(p=dropout)
- pe = torch.zeros(max_len, d_model)
- position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
- div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
- pe[:, 0::2] = torch.sin(position * div_term)
- pe[:, 1::2] = torch.cos(position * div_term)
- pe = pe.unsqueeze(0)
- self.register_buffer('pe', pe)
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- x = x + self.pe[:, :x.size(1), :]
- return self.dropout(x)
- class KnowledgeGuidance(nn.Module):
- """
- Knowledge guidance mechanism integrating explicit and implicit knowledge.
- Implements Equations (9), (14), (15), (18), (19), (20) from the paper.
- """
- def __init__(self,
- personality_dim: int = 5,
- rule_vocab_size: int = 100,
- embed_dim: int = 256,
- feature_dim: int = 512,
- num_heads: int = 8):
- super().__init__()
- # Personality trait encoding (Equation 18)
- self.personality_encoder = nn.Sequential(
- nn.Linear(personality_dim, embed_dim),
- nn.ReLU(),
- nn.Linear(embed_dim, embed_dim)
- )
- # Domain rule embedding (Equation 19)
- self.rule_embedding = nn.Embedding(rule_vocab_size, embed_dim)
- # Explicit knowledge fusion (Equation 20)
- self.alpha = 0.6 # Weight for personality
- self.beta = 0.4 # Weight for domain rules
- # Knowledge-guided attention (Equation 14)
- self.knowledge_attention = nn.MultiheadAttention(
- embed_dim=feature_dim,
- num_heads=num_heads,
- batch_first=True
- )
- # Project knowledge to feature dimension
- self.knowledge_proj = nn.Linear(embed_dim * 2, feature_dim)
- def forward(self,
- features: torch.Tensor,
- personality: torch.Tensor,
- rule_ids: torch.Tensor) -> torch.Tensor:
- """
- Args:
- features: Feature tensor (batch, seq_len, feature_dim)
- personality: Personality traits (batch, 5) - Big Five
- rule_ids: Domain rule indices (batch,)
- Returns:
- Knowledge-weighted features (batch, seq_len, feature_dim)
- """
- # Encode personality traits
- K_p = self.personality_encoder(personality) # (batch, embed_dim)
- # Encode domain rules
- K_r = self.rule_embedding(rule_ids) # (batch, embed_dim)
- # Fuse explicit knowledge (Equation 20)
- K_explicit = self.alpha * K_p + self.beta * K_r # (batch, embed_dim)
- # Concatenate with implicit knowledge placeholder
- # In practice, implicit knowledge would be distilled from LLM
- K_implicit = torch.zeros_like(K_explicit)
- K = torch.cat([K_explicit, K_implicit], dim=-1) # (batch, embed_dim * 2)
- # Project knowledge to feature dimension
- K_proj = self.knowledge_proj(K).unsqueeze(1) # (batch, 1, feature_dim)
- # Knowledge-guided attention (Equation 14)
- attn_output, _ = self.knowledge_attention(
- K_proj, features, features
- )
- # Combine with original features
- output = features + attn_output.expand(-1, features.size(1), -1)
- return output
- class DynamicContextWindow(nn.Module):
- """
- Dynamic context window that adapts based on emotional shift intensity.
- Implements Equation (10) from the paper.
- """
- def __init__(self,
- min_window: int = 3,
- max_window: int = 10,
- shift_threshold_high: float = 0.6,
- shift_threshold_low: float = 0.2):
- super().__init__()
- self.min_window = min_window
- self.max_window = max_window
- self.shift_threshold_high = shift_threshold_high
- self.shift_threshold_low = shift_threshold_low
- def compute_window_size(self, emotional_shift: torch.Tensor) -> int:
- """
- Compute dynamic window size based on emotional shift intensity.
- Args:
- emotional_shift: Emotional shift intensity (batch,)
- Returns:
- Window size (int)
- """
- # Apply thresholds as specified in paper
- if emotional_shift.mean() > self.shift_threshold_high:
- return self.min_window # W=3 for rapid changes
- elif emotional_shift.mean() < self.shift_threshold_low:
- return self.max_window # W=10 for stable periods
- else:
- return 5 # Medium window for moderate shifts
- def forward(self,
- features: torch.Tensor,
- emotional_shifts: torch.Tensor) -> torch.Tensor:
- """
- Apply dynamic window filtering.
- Args:
- features: Feature sequence (batch, seq_len, feature_dim)
- emotional_shifts: Emotional shift intensities (batch, seq_len)
- Returns:
- Window-filtered features (batch, feature_dim)
- """
- batch_size, seq_len, feature_dim = features.shape
- # Compute window size for each sample
- window_sizes = []
- for i in range(batch_size):
- w = self.compute_window_size(emotional_shifts[i])
- window_sizes.append(w)
- # Apply window filtering with sigmoid weighting
- outputs = []
- for i in range(batch_size):
- w = min(window_sizes[i], seq_len)
- window_feats = features[i, -w:, :] # Take last w features
- # Compute sigmoid weights based on emotional shifts
- shifts = emotional_shifts[i, -w:]
- weights = torch.sigmoid(shifts).unsqueeze(-1) # (w, 1)
- # Weighted aggregation
- weighted_feat = (window_feats * weights).sum(dim=0) / (weights.sum() + 1e-8)
- outputs.append(weighted_feat)
- return torch.stack(outputs)
- class ContextualSentimentModel(nn.Module):
- """
- Complete contextual sentiment recognition model.
- Integrates all components: multimodal encoder, contextual encoder,
- knowledge guidance, and dynamic context window.
- """
- def __init__(self,
- num_emotions: int = 7,
- text_dim: int = 768,
- speech_dim: int = 512,
- video_dim: int = 256,
- hidden_dim: int = 1536,
- context_dim: int = 512,
- num_context_layers: int = 3,
- num_heads: int = 8,
- dropout: float = 0.1):
- super().__init__()
- self.num_emotions = num_emotions
- # Multimodal feature encoder
- self.multimodal_encoder = MultimodalFeatureEncoder(
- text_dim=text_dim,
- speech_dim=speech_dim,
- video_dim=video_dim,
- hidden_dim=hidden_dim
- )
- # Contextual encoder
- self.contextual_encoder = ContextualEncoder(
- input_dim=hidden_dim,
- hidden_dim=context_dim,
- num_layers=num_context_layers,
- num_heads=num_heads,
- dropout=dropout
- )
- # Knowledge guidance
- self.knowledge_guidance = KnowledgeGuidance(
- feature_dim=context_dim
- )
- # Dynamic context window
- self.dynamic_window = DynamicContextWindow()
- # Feature fusion (Equation 9)
- self.fusion_alpha = 0.4 # Multimodal weight
- self.fusion_beta = 0.3 # Contextual weight
- self.fusion_gamma = 0.3 # Knowledge weight
- # Fusion projection
- self.fusion_proj = nn.Sequential(
- nn.Linear(hidden_dim + context_dim * 2, hidden_dim),
- nn.LayerNorm(hidden_dim),
- nn.ReLU(),
- nn.Dropout(dropout)
- )
- # Classification head
- self.classifier = nn.Sequential(
- nn.Linear(hidden_dim, hidden_dim // 2),
- nn.ReLU(),
- nn.Dropout(dropout),
- nn.Linear(hidden_dim // 2, num_emotions)
- )
- # Emotional shift predictor for dynamic window
- self.shift_predictor = nn.Linear(context_dim, 1)
- def forward(self,
- text: torch.Tensor,
- speech: torch.Tensor,
- video: torch.Tensor,
- personality: torch.Tensor,
- rule_ids: torch.Tensor,
- context_mask: Optional[torch.Tensor] = None) -> Dict[str, torch.Tensor]:
- """
- Forward pass of the model.
- Args:
- text: Text features (batch, seq_len, text_dim)
- speech: Speech features (batch, seq_len, speech_dim, seq_len2)
- video: Video features (batch, seq_len, video_dim, seq_len2)
- personality: Personality traits (batch, 5)
- rule_ids: Domain rule indices (batch,)
- context_mask: Optional mask for context (batch, seq_len)
- Returns:
- Dictionary containing logits, emotional shifts, and intermediate features
- """
- batch_size, seq_len = text.shape[:2]
- # Encode multimodal features for each turn
- multimodal_feats = []
- for t in range(seq_len):
- # Extract features for turn t
- text_t = text[:, t, :] # (batch, text_dim)
- speech_t = speech[:, t, :, :] # (batch, speech_dim, seq_len2)
- video_t = video[:, t, :, :] # (batch, video_dim, seq_len2)
- # Encode multimodal features
- mm_feat = self.multimodal_encoder(text_t, speech_t, video_t)
- multimodal_feats.append(mm_feat)
- multimodal_feats = torch.stack(multimodal_feats, dim=1) # (batch, seq_len, hidden_dim)
- # Encode contextual features
- context_feats = self.contextual_encoder(multimodal_feats, mask=context_mask)
- # (batch, seq_len, context_dim)
- # Apply knowledge guidance
- knowledge_feats = self.knowledge_guidance(context_feats, personality, rule_ids)
- # (batch, seq_len, context_dim)
- # Predict emotional shifts for dynamic window
- emotional_shifts = self.shift_predictor(knowledge_feats).squeeze(-1)
- # (batch, seq_len)
- emotional_shifts = torch.sigmoid(emotional_shifts)
- # Apply dynamic context window
- windowed_feats = self.dynamic_window(knowledge_feats, emotional_shifts)
- # (batch, context_dim)
- # Get last multimodal feature
- last_mm_feat = multimodal_feats[:, -1, :] # (batch, hidden_dim)
- # Get last contextual feature
- last_ctx_feat = context_feats[:, -1, :] # (batch, context_dim)
- # Feature fusion (Equation 9)
- fused = torch.cat([last_mm_feat, last_ctx_feat, windowed_feats], dim=-1)
- fused = self.fusion_proj(fused)
- # Classification
- logits = self.classifier(fused)
- return {
- 'logits': logits,
- 'emotional_shifts': emotional_shifts,
- 'multimodal_feats': multimodal_feats,
- 'context_feats': context_feats,
- 'fused_feats': fused
- }
- class LightweightContextualSentimentModel(nn.Module):
- """
- Lightweight version of the model with reduced parameters.
- 18.2M parameters vs 36.8M in full version.
- """
- def __init__(self,
- num_emotions: int = 7,
- text_dim: int = 768,
- speech_dim: int = 512,
- video_dim: int = 256,
- hidden_dim: int = 768,
- context_dim: int = 256,
- num_context_layers: int = 2,
- num_heads: int = 4,
- dropout: float = 0.1):
- super().__init__()
- # Simplified multimodal encoder
- self.text_proj = nn.Linear(text_dim, hidden_dim // 3)
- self.speech_proj = nn.Linear(speech_dim, hidden_dim // 3)
- self.video_proj = nn.Linear(video_dim, hidden_dim // 3)
- # Simplified contextual encoder
- self.context_encoder = nn.LSTM(
- input_size=hidden_dim,
- hidden_size=context_dim,
- num_layers=2,
- batch_first=True,
- dropout=dropout,
- bidirectional=True
- )
- # Simplified classifier
- self.classifier = nn.Sequential(
- nn.Linear(hidden_dim + context_dim * 2, hidden_dim // 2),
- nn.ReLU(),
- nn.Dropout(dropout),
- nn.Linear(hidden_dim // 2, num_emotions)
- )
- def forward(self,
- text: torch.Tensor,
- speech: torch.Tensor,
- video: torch.Tensor,
- personality: Optional[torch.Tensor] = None,
- rule_ids: Optional[torch.Tensor] = None,
- context_mask: Optional[torch.Tensor] = None) -> Dict[str, torch.Tensor]:
- """
- Simplified forward pass for lightweight model.
- """
- batch_size, seq_len = text.shape[:2]
- # Simple multimodal fusion
- multimodal_feats = []
- for t in range(seq_len):
- text_t = self.text_proj(text[:, t, :])
- speech_t = self.speech_proj(speech[:, t, :, :].mean(dim=-1))
- video_t = self.video_proj(video[:, t, :, :].mean(dim=-1))
- fused = torch.cat([text_t, speech_t, video_t], dim=-1)
- multimodal_feats.append(fused)
- multimodal_feats = torch.stack(multimodal_feats, dim=1)
- # LSTM contextual encoding
- context_feats, _ = self.context_encoder(multimodal_feats)
- # Classification
- combined = torch.cat([
- multimodal_feats[:, -1, :],
- context_feats[:, -1, :]
- ], dim=-1)
- logits = self.classifier(combined)
- return {
- 'logits': logits,
- 'emotional_shifts': torch.zeros(batch_size, seq_len),
- 'multimodal_feats': multimodal_feats,
- 'context_feats': context_feats,
- 'fused_feats': combined
- }
- def count_parameters(model: nn.Module) -> int:
- """Count the number of trainable parameters in a model."""
- return sum(p.numel() for p in model.parameters() if p.requires_grad)
- if __name__ == "__main__":
- # Test the model
- print("Testing Contextual Sentiment Model...")
- # Create model
- model = ContextualSentimentModel(num_emotions=7)
- # Count parameters
- num_params = count_parameters(model)
- print(f"Full model parameters: {num_params / 1e6:.1f}M")
- # Test forward pass
- batch_size = 4
- seq_len = 10
- text = torch.randn(batch_size, seq_len, 768)
- speech = torch.randn(batch_size, seq_len, 512, 50)
- video = torch.randn(batch_size, seq_len, 256, 50)
- personality = torch.randn(batch_size, 5)
- rule_ids = torch.randint(0, 100, (batch_size,))
- output = model(text, speech, video, personality, rule_ids)
- print(f"Logits shape: {output['logits'].shape}")
- print(f"Emotional shifts shape: {output['emotional_shifts'].shape}")
- # Test lightweight model
- light_model = LightweightContextualSentimentModel(num_emotions=7)
- light_params = count_parameters(light_model)
- print(f"\nLightweight model parameters: {light_params / 1e6:.1f}M")
- light_output = light_model(text, speech, video)
- print(f"Lightweight logits shape: {light_output['logits'].shape}")
model.py, no license · at the source
Overview
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/
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
Availability: 1 check, the latest on 28 September 2026: the link answers (HTTP 200)
- 28 September 2026: the link answers (HTTP 200)
22 files
- Result Export.py, Python, 422 lines
- Training Pipeline .py, Python, 389 lines, 1 match
- complete_experiment/
run_all_experiments.sh , Shell, 115 lines - complete_experiment/
scripts/ , Python, 193 linesgenerate_figures.py - complete_experiment/
scripts/ , Python, 259 lines, 5 matchesgenerate_tables.py - complete_experiment/
src/ , Python, 535 lines, 1 matchdata/ preprocessor.py - complete_experiment/
src/ , Python, 306 lines, 1 matchdata/ smote_balancing.py - complete_experiment/
src/ , Python, 291 linesevaluation/ ablation.py - complete_experiment/
src/ , Python, 331 linesevaluation/ evaluate.py - complete_experiment/
src/ , Python, 136 linesevaluation/ statistical_tests.py - complete_experiment/
src/ , Python, 628 lines, 1 matchtraining/ trainer.py - config.py, Python, 417 lines, 4 matches
- data_loader.py, Python, 497 lines
- evaluate.py, Python, 517 lines, 1 match
- generate_data.py, Python, 445 lines, 4 matches
- main.py, Python, 354 lines, 2 matches
- model.py, Python, 617 lines, 7 matches
- notebooks/
01_data_exploration.ipyn , Jupyter, 171 lines, 1 matchb - notebooks/
06_visualization.ipynb , Jupyter, 289 lines - scripts/
run_all_experiments.sh , Shell, 138 lines - train.py, Python, 570 lines, 6 matches
- README.md, Text, 195 lines
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
- huggingface.co/
datasets/ , at Hugging Face; found in the text, “Experimental setup”li2017dailydialog/ daily_dialog - huggingface.co/
datasets/ , at Hugging Face; found in the text, “Experimental setup”zrr1999/ meld_text
Data availability
The datasets supporting the findings of this study are publicly available. The IEMOCAP dataset is accessible from its official website (https://
Data and code are available via the following link: https://
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://
BibTeX
@article{cheng2026resear
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/
url = {https://
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/
VL - 16
IS - 1
SP - 22104
SN - 2045-2322
PB - Nature Publishing Group
DO - 10.1038/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.1038/
"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":
"volume": "16",
"issue": "1",
"page": "22104",
"DOI": "10.1038/
"PMID": "42135370",
"PMCID": "PMC13369197",
"ISSN": "2045-2322",
"publisher": "Nature Publishing Group",
"URL": "https://
"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 biologyIn 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 communicationsIn 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 communicationsIn 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 communicationsIn 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 medicineIn 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: eLifeIn 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 mappingIn 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 medicineIn 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 reportsIn 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 biologyIn 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.
Claim this paper
Correct its record
Say what each link of this record is, remove the ones that are not the paper's, add the ones that are missing. The correction becomes a new version of the record, in its Versions section.
Validate its tracing map
You validate the map as this page shows it: 1 repository of the authors' code, each at its verified commit and with its license, 21 scripts, and 34 matches between paragraphs and code (see the Code and Map sections). It then receives a DOI on Zenodo, with you (your ORCID iD) and OSCR as its creators; the code itself is not deposited.
The map's fingerprint: sha256:3f40bd3917083e2d…
Add the badge to its README
The badge links the code to this page. Copy one of these into the README of the paper's code: only you decide where it goes, and nothing is changed for you.
Markdown
[.
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.
