Spaces:
Sleeping
Sleeping
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| class ResNetBlock(nn.Module): | |
| def __init__(self, in_channels, out_channels, stride=1, downsample=None): | |
| super(ResNetBlock, self).__init__() | |
| self.conv1 = nn.Conv1d(in_channels, out_channels, kernel_size=7, stride=stride, padding=3, bias=False) | |
| self.bn1 = nn.BatchNorm1d(out_channels) | |
| self.relu = nn.ReLU(inplace=True) | |
| self.conv2 = nn.Conv1d(out_channels, out_channels, kernel_size=7, stride=1, padding=3, bias=False) | |
| self.bn2 = nn.BatchNorm1d(out_channels) | |
| self.downsample = downsample | |
| def forward(self, x): | |
| identity = x | |
| if self.downsample is not None: | |
| identity = self.downsample(x) | |
| out = self.conv1(x) | |
| out = self.bn1(out) | |
| out = self.relu(out) | |
| out = self.conv2(out) | |
| out = self.bn2(out) | |
| out += identity | |
| out = self.relu(out) | |
| return out | |
| class ResNet1d(nn.Module): | |
| """ | |
| ResNet-1D for ECG Classification. | |
| Adapted from 'Time Series Classification from Scratch with Deep Neural Networks: A Strong Baseline' (Wang et al. 2017) | |
| """ | |
| def __init__(self, num_classes=5): | |
| super(ResNet1d, self).__init__() | |
| self.inplanes = 64 | |
| # Initial: 12 leads -> 64 channels | |
| self.conv1 = nn.Conv1d(12, 64, kernel_size=15, stride=2, padding=7, bias=False) | |
| self.bn1 = nn.BatchNorm1d(64) | |
| self.relu = nn.ReLU(inplace=True) | |
| self.maxpool = nn.MaxPool1d(kernel_size=3, stride=2, padding=1) | |
| # Layers | |
| self.layer1 = self._make_layer(64, 2, stride=1) | |
| self.layer2 = self._make_layer(128, 2, stride=2) | |
| self.layer3 = self._make_layer(256, 2, stride=2) | |
| self.layer4 = self._make_layer(512, 2, stride=2) | |
| self.avgpool = nn.AdaptiveAvgPool1d(1) | |
| self.fc = nn.Linear(512, num_classes) | |
| def _make_layer(self, planes, blocks, stride=1): | |
| downsample = None | |
| if stride != 1 or self.inplanes != planes: | |
| downsample = nn.Sequential( | |
| nn.Conv1d(self.inplanes, planes, kernel_size=1, stride=stride, bias=False), | |
| nn.BatchNorm1d(planes), | |
| ) | |
| layers = [] | |
| layers.append(ResNetBlock(self.inplanes, planes, stride, downsample)) | |
| self.inplanes = planes | |
| for _ in range(1, blocks): | |
| layers.append(ResNetBlock(self.inplanes, planes)) | |
| return nn.Sequential(*layers) | |
| def forward(self, x): | |
| x = self.conv1(x) | |
| x = self.bn1(x) | |
| x = self.relu(x) | |
| x = self.maxpool(x) | |
| x = self.layer1(x) | |
| x = self.layer2(x) | |
| x = self.layer3(x) | |
| x = self.layer4(x) | |
| x = self.avgpool(x) | |
| x = x.view(x.size(0), -1) | |
| x = self.fc(x) | |
| return x | |
| if __name__ == "__main__": | |
| # Test | |
| model = ResNet1d(num_classes=5) | |
| dummy = torch.randn(2, 12, 5000) | |
| out = model(dummy) | |
| print(f"Input: {dummy.shape}") | |
| print(f"Output: {out.shape}") | |