afnrmdhn
initial commit
9950952
Raw History Blame Contribute Delete
12.9 kB
import torch
from torch import nn
from torch.nn import functional as F
class LSTMModel(nn.Module):
def __init__(self, input_dim, hidden_dim, num_layers, num_heads, num_classes, dropout):
super(LSTMModel, self).__init__()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.projection = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.BatchNorm1d(hidden_dim),
nn.ReLU(),
nn.Dropout(dropout)
)
self.lstm1 = nn.LSTM(
hidden_dim,
hidden_dim,
num_layers,
batch_first=True,
bidirectional=True,
dropout=dropout if num_layers > 1 else 0
)
self.lstm2 = nn.LSTM(
hidden_dim * 2,
hidden_dim,
num_layers,
batch_first=True,
bidirectional=True,
dropout=dropout if num_layers > 1 else 0
)
self.attention1 = nn.MultiheadAttention(
hidden_dim*2,
num_heads,
batch_first=True
)
self.attention2 = nn.MultiheadAttention(
hidden_dim*2,
num_heads,
batch_first=True
)
self.fc = nn.Sequential(
nn.Linear(hidden_dim*4, hidden_dim),
nn.BatchNorm1d(hidden_dim),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(hidden_dim, hidden_dim // 2),
nn.BatchNorm1d(hidden_dim // 2),
nn.ReLU(),
nn.Linear(hidden_dim // 2, num_classes)
)
self.apply(self.init_weights)
def init_weights(self, module):
if isinstance(module, nn.Linear):
nn.init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu')
if module.bias is not None:
nn.init.constant_(module.bias, 0)
elif isinstance(module, nn.LSTM):
for name, param in module.named_parameters():
if "weight_ih" in name or "weight_hh" in name:
nn.init.orthogonal_(param.data)
elif "bias" in name:
param.data.fill_(0)
elif isinstance(module, nn.BatchNorm1d):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
def forward(self, x):
batch_size, seq_len, _ = x.shape
x_flat = x.view(-1, self.input_dim)
x_projected = self.projection(x_flat)
x_projected = x_projected.view(batch_size, seq_len, self.hidden_dim)
x_lstm1, _ = self.lstm1(x_projected)
x_att1, _ = self.attention1(x_lstm1, x_lstm1, x_lstm1)
x_lstm2, _ = self.lstm2(x_lstm1)
x_att2, _ = self.attention2(x_lstm2, x_lstm2, x_lstm2)
attention1 = x_att1[:,-1,:]
attention2 = x_att2[:,-1,:]
output = self.fc(torch.cat((attention1, attention2), dim=1))
return output
def _init_weights(module):
if isinstance(module, (nn.Linear, nn.Conv1d)):
nn.init.kaiming_normal_(module.weight, mode='fan_in', nonlinearity='relu')
if module.bias is not None:
nn.init.zeros_(module.bias)
elif isinstance(module, nn.LayerNorm):
nn.init.ones_(module.weight)
nn.init.zeros_(module.bias)
elif isinstance(module, nn.BatchNorm1d):
module.weight.data.fill_(1.0)
module.bias.data.zero_()
class DepthwiseSeparableConv(nn.Module):
def __init__(self, input_dim, out_channels, kernel_size, stride=1, padding=0):
super().__init__()
self.depthwise = nn.Conv1d(input_dim, input_dim, kernel_size, stride=stride, padding=padding, groups=input_dim, bias=True)
self.pointwise = nn.Conv1d(input_dim, out_channels, kernel_size=1, bias=True)
self.norm = nn.BatchNorm1d(out_channels)
def forward(self, x):
x = self.depthwise(x)
x = self.pointwise(x)
x = self.norm(x)
return F.gelu(x)
class MultiScaleEncoder(nn.Module):
def __init__(self, input_dim=128, hidden_dim=64, dropout=0.2):
super().__init__()
self.projection = nn.Linear(input_dim, hidden_dim)
assert hidden_dim % 4 == 0, "hidden_dim must be divisible by 4"
out_channels = hidden_dim // 4
self.conv3 = DepthwiseSeparableConv(hidden_dim, out_channels, kernel_size=3, padding=1)
self.conv5 = DepthwiseSeparableConv(hidden_dim, out_channels, kernel_size=5, padding=2)
self.conv7 = DepthwiseSeparableConv(hidden_dim, out_channels, kernel_size=7, padding=3)
self.adv_pool = nn.AdaptiveAvgPool1d(30)
self.fusion = nn.Sequential(
nn.Linear(out_channels*3, hidden_dim),
nn.GELU(),
nn.Dropout(dropout)
)
self.apply(_init_weights)
def forward(self, x):
B, T, F = x.shape
x = self.projection(x)
x_t = x.transpose(1, 2)
f3 = self.conv3(x_t)
f5 = self.conv5(x_t)
f7 = self.conv7(x_t)
f3 = self.adv_pool(f3)
f5 = self.adv_pool(f5)
f7 = self.adv_pool(f7)
features = torch.cat([f3, f5, f7], dim=1)
features = features.transpose(1, 2)
return self.fusion(features)
class LinearAttention(nn.Module):
def __init__(self, dim, heads=4, dropout=0.1):
super().__init__()
assert dim % heads == 0, "Dimension must be divisible by number of heads"
self.heads = heads
self.head_dim = dim // heads
self.scale = dim ** -0.5
self.to_qkv = nn.Linear(dim, dim * 3, bias=False)
self.to_out = nn.Linear(dim, dim)
self.dropout = nn.Dropout(dropout)
self.apply(_init_weights)
def forward(self, x):
B, T, D = x.shape
qkv = self.to_qkv(x).chunk(3, dim=-1)
q, k, v = map(lambda t: t.reshape(B, T, self.heads, -1).transpose(1, 2), qkv)
k = F.softmax(k, dim=-1)
context = torch.einsum('bhnd,bhne->bhde', k, v)
out = torch.einsum('bhnd,bhde->bhne', q, context)
out = out.transpose(1, 2).reshape(B, T, D)
return self.dropout(self.to_out(out))
class FFN(nn.Module):
def __init__(self, dim, expansion_factor=4, dropout=0.1):
super().__init__()
hidden_dim = int(dim * expansion_factor)
self.net = nn.Sequential(
nn.Linear(dim, hidden_dim),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(hidden_dim, dim),
nn.Dropout(dropout)
)
self.apply(_init_weights)
def forward(self, x):
return self.net(x)
class TransformerBlock(nn.Module):
def __init__(self, dim, heads=4, dropout=0.1):
super().__init__()
self.norm1 = nn.LayerNorm(dim)
self.attn = LinearAttention(dim, heads, dropout)
self.norm2 = nn.LayerNorm(dim)
self.ffn = FFN(dim, expansion_factor=1.5, dropout=dropout)
def forward(self, x):
x = x + self.attn(self.norm1(x))
x = x + self.ffn(self.norm2(x))
return x
class TemporalPoolingBlock(nn.Module):
def __init__(self, dim, pool_type='attention'):
super().__init__()
self.pool_type = pool_type
if pool_type == 'attention':
self.attention = nn.Sequential(
nn.Linear(dim, max(dim//4, 1)),
nn.Tanh(),
nn.Linear(max(dim//4, 1), 1),
nn.Softmax(dim=1)
)
elif pool_type == 'learnable':
self.weights = nn.Parameter(torch.ones(1, 30,1))
self.apply(_init_weights)
def forward(self, x):
if self.pool_type == 'mean':
return x.mean(dim=1)
elif self.pool_type == 'max':
return x.max(dim=1).values
elif self.pool_type == 'attention':
attn_weights = self.attention(x)
return (x * attn_weights).sum(dim=1)
elif self.pool_type == 'learnable':
weights = F.softmax(self.weights, dim=1)
return (x * weights).sum(dim=1)
class TransformerModel(nn.Module):
def __init__(self, input_dim, seq_len, hidden_dim, num_layers, num_heads, dropout, num_classes, pool_type='attention'):
super().__init__()
assert hidden_dim % 4 == 0, "hidden_dim must be divisible by 4"
self.input_dim = input_dim
self.seq_len = seq_len
self.hidden_dim = hidden_dim
self.encoder = MultiScaleEncoder(input_dim, hidden_dim, dropout)
encoder_out_dim = hidden_dim
self.pos_embedding = nn.Parameter(torch.randn(1, 30, encoder_out_dim)*0.02)
self.transformer_layer = nn.ModuleList([
TransformerBlock(encoder_out_dim, num_heads, dropout)
for _ in range(num_layers)
])
self.transformer_norm = nn.LayerNorm(encoder_out_dim)
self.pooling = TemporalPoolingBlock(encoder_out_dim, pool_type)
self.classifier = nn.Sequential(
nn.Linear(encoder_out_dim, encoder_out_dim//2),
nn.GELU(),
nn.Dropout(dropout*1.5),
nn.Linear(encoder_out_dim//2, num_classes),
)
self.aux_classifier = None
if num_layers >= 4:
self.aux_classifier = nn.Linear(encoder_out_dim, num_classes)
self.apply(_init_weights)
def forward(self, x):
x = self.encoder(x)
x = x + self.pos_embedding
features = []
for _ , layer in enumerate(self.transformer_layer):
x = layer(x)
features.append(x)
x = self.transformer_norm(x)
x_pool = self.pooling(x)
logits = self.classifier(x_pool)
if self.aux_classifier is not None and self.training:
mid_layer = len(features) // 2
aux_pool = self.pooling(features[mid_layer])
aux_logits = self.aux_classifier(aux_pool)
return logits, aux_logits
return logits
class LSTMModel(nn.Module):
def __init__(self, input_dim, hidden_dim, num_layers, num_heads, num_classes, dropout):
super(LSTMModel, self).__init__()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.projection = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.BatchNorm1d(hidden_dim),
nn.ReLU(),
nn.Dropout(dropout)
)
self.lstm1 = nn.LSTM(
hidden_dim,
hidden_dim,
num_layers,
batch_first=True,
bidirectional=True,
dropout=dropout if num_layers > 1 else 0
)
self.lstm2 = nn.LSTM(
hidden_dim * 2,
hidden_dim,
num_layers,
batch_first=True,
bidirectional=True,
dropout=dropout if num_layers > 1 else 0
)
self.attention1 = nn.MultiheadAttention(
hidden_dim*2,
num_heads,
batch_first=True
)
self.attention2 = nn.MultiheadAttention(
hidden_dim*2,
num_heads,
batch_first=True
)
self.fc = nn.Sequential(
nn.Linear(hidden_dim*4, hidden_dim),
nn.BatchNorm1d(hidden_dim),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(hidden_dim, hidden_dim // 2),
nn.BatchNorm1d(hidden_dim // 2),
nn.ReLU(),
nn.Linear(hidden_dim // 2, num_classes)
)
self.apply(self.init_weights)
def init_weights(self, module):
if isinstance(module, nn.Linear):
nn.init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu')
if module.bias is not None:
nn.init.constant_(module.bias, 0)
elif isinstance(module, nn.LSTM):
for name, param in module.named_parameters():
if "weight_ih" in name or "weight_hh" in name:
nn.init.orthogonal_(param.data)
elif "bias" in name:
param.data.fill_(0)
elif isinstance(module, nn.BatchNorm1d):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
def forward(self, x):
batch_size, seq_len, _ = x.shape
x_flat = x.view(-1, self.input_dim)
x_projected = self.projection(x_flat)
x_projected = x_projected.view(batch_size, seq_len, self.hidden_dim)
x_lstm1, _ = self.lstm1(x_projected)
x_att1, _ = self.attention1(x_lstm1, x_lstm1, x_lstm1)
x_lstm2, _ = self.lstm2(x_lstm1)
x_att2, _ = self.attention2(x_lstm2, x_lstm2, x_lstm2)
attention1 = x_att1[:,-1,:]
attention2 = x_att2[:,-1,:]
output = self.fc(torch.cat((attention1, attention2), dim=1))
return output