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
| import torch import torch.nn as nn
class DCDDModel(nn.Module): def __init__(self, feature_dim=64, hidden_dim=128, num_classes=2): super().__init__() self.spatial_cnn = nn.Sequential( nn.Conv1d(feature_dim, 128, kernel_size=3, padding=1), nn.ReLU(), nn.Conv1d(128, 128, kernel_size=3, padding=1), nn.ReLU(), ) self.temporal_lstm = nn.LSTM( input_size=128, hidden_size=hidden_dim, num_layers=2, batch_first=True, bidirectional=True ) self.attention = nn.Sequential( nn.Linear(hidden_dim * 2, 64), nn.Tanh(), nn.Linear(64, 1), nn.Softmax(dim=1) ) self.classifier = nn.Sequential( nn.Linear(hidden_dim * 2, 64), nn.ReLU(), nn.Dropout(0.3), nn.Linear(64, num_classes) ) def forward(self, x): """ x: [batch, seq_len, feature_dim] """ x = x.permute(0, 2, 1) spatial_feat = self.spatial_cnn(x) spatial_feat = spatial_feat.permute(0, 2, 1) temporal_feat, _ = self.temporal_lstm(spatial_feat) attn_weights = self.attention(temporal_feat) weighted_feat = (temporal_feat * attn_weights).sum(dim=1) output = self.classifier(weighted_feat) return output
|