File size: 11,756 Bytes
8133f1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
"""
ST-GCN Model for Fall Detection

Spatial-Temporal Graph Convolutional Networks for skeleton-based action recognition.
Adapted for binary fall detection (Fall vs Non-Fall) and multi-class fall type classification.

References:
- ST-GCN Paper: https://arxiv.org/abs/1801.07455
- Official Implementation: https://github.com/yysijie/st-gcn
- Fall Detection: Keskes & Noumeir (2021)

Input Shape: (N, C, T, V, M)
- N: Batch size
- C: Number of channels (3: x, y, confidence)
- T: Temporal dimension (number of frames)
- V: Number of vertices (17 COCO keypoints)
- M: Number of persons (1 for single-person scenarios)

Output: Class logits for Fall/Non-Fall (binary) or BY/FY/SY/N (multi-class)
"""

import torch
import torch.nn as nn
import torch.nn.functional as F

from .graph import Graph


class STGCNLayer(nn.Module):
    """
    Spatial-Temporal Graph Convolutional Layer.

    Combines spatial graph convolution and temporal convolution.
    """

    def __init__(
        self,
        in_channels,
        out_channels,
        kernel_size,
        stride=1,
        dropout=0.5,
        residual=True
    ):
        """
        Initialize ST-GCN layer.

        Args:
            in_channels: Number of input channels
            out_channels: Number of output channels
            kernel_size: Tuple (temporal_kernel_size, spatial_kernel_size)
            stride: Temporal stride for downsampling
            dropout: Dropout probability
            residual: Whether to use residual connection
        """
        super(STGCNLayer, self).__init__()

        assert len(kernel_size) == 2, "Kernel size must be (temporal, spatial)"
        assert kernel_size[0] % 2 == 1, "Temporal kernel size must be odd"

        padding = ((kernel_size[0] - 1) // 2, 0)  # Temporal padding only

        # Spatial graph convolution
        self.gcn = SpatialGraphConv(
            in_channels,
            out_channels,
            kernel_size[1]
        )

        # Temporal convolution
        self.tcn = nn.Sequential(
            nn.BatchNorm2d(out_channels),
            nn.ReLU(inplace=True),
            nn.Conv2d(
                out_channels,
                out_channels,
                (kernel_size[0], 1),
                (stride, 1),
                padding,
            ),
            nn.BatchNorm2d(out_channels),
            nn.Dropout(dropout, inplace=True),
        )

        # Residual connection
        if not residual:
            self.residual = lambda x: 0
        elif (in_channels == out_channels) and (stride == 1):
            self.residual = lambda x: x
        else:
            self.residual = nn.Sequential(
                nn.Conv2d(
                    in_channels,
                    out_channels,
                    kernel_size=1,
                    stride=(stride, 1)
                ),
                nn.BatchNorm2d(out_channels),
            )

        self.relu = nn.ReLU(inplace=True)

    def forward(self, x, A):
        """
        Forward pass.

        Args:
            x: Input tensor (N, C, T, V)
            A: Adjacency matrix (K, V, V) where K is number of partitions

        Returns:
            Output tensor (N, C', T', V)
        """
        res = self.residual(x)
        x = self.gcn(x, A)
        x = self.tcn(x) + res

        return self.relu(x)


class SpatialGraphConv(nn.Module):
    """
    Spatial graph convolutional layer.

    Applies graph convolution on skeleton graph using adjacency matrix.
    """

    def __init__(self, in_channels, out_channels, kernel_size, bias=True):
        """
        Initialize spatial graph convolution.

        Args:
            in_channels: Number of input channels
            out_channels: Number of output channels
            kernel_size: Number of adjacency matrix partitions (1 or 3)
            bias: Whether to include bias term
        """
        super(SpatialGraphConv, self).__init__()

        self.kernel_size = kernel_size

        # Convolutional weights for each partition
        self.conv = nn.Conv2d(
            in_channels,
            out_channels * kernel_size,
            kernel_size=1,
            bias=bias
        )

    def forward(self, x, A):
        """
        Forward pass.

        Args:
            x: Input tensor (N, C, T, V)
            A: Adjacency matrix (K, V, V)

        Returns:
            Output tensor (N, C', T, V)
        """
        assert A.size(0) == self.kernel_size, \
            f"Adjacency matrix size {A.size(0)} != kernel size {self.kernel_size}"

        # Apply convolution
        x = self.conv(x)  # (N, C'*K, T, V)

        # Split channels for each partition
        n, kc, t, v = x.size()
        x = x.view(n, self.kernel_size, kc // self.kernel_size, t, v)  # (N, K, C', T, V)

        # Apply graph convolution with each partition
        # A: (K, V, V)
        # x: (N, K, C', T, V)
        x = torch.einsum('nkctv,kvw->nctw', x, A)  # (N, C', T, V)

        return x.contiguous()


class STGCN(nn.Module):
    """
    ST-GCN model for fall detection.

    Architecture:
    - Input: (N, 3, 60, 17, 1) - batch, channels, frames, joints, persons
    - ST-GCN layers: Extract spatial-temporal features
    - Global pooling: Aggregate features across time and space
    - FC layers: Classification (binary or multi-class)
    """

    def __init__(
        self,
        num_classes=2,
        in_channels=3,
        edge_importance_weighting=True,
        graph_cfg=None,
        dropout=0.5,
        **kwargs
    ):
        """
        Initialize ST-GCN model.

        Args:
            num_classes: Number of output classes (2 for binary, 4 for multi-class)
            in_channels: Number of input channels (3: x, y, confidence)
            edge_importance_weighting: Whether to learn edge importance weights
            graph_cfg: Graph configuration (default: spatial labeling)
            dropout: Dropout probability
        """
        super(STGCN, self).__init__()

        # Load graph
        if graph_cfg is None:
            graph_cfg = {'labeling_mode': 'spatial'}

        self.graph = Graph(**graph_cfg)

        # Get adjacency matrix (K, V, V) where K=3 for spatial labeling
        A = torch.tensor(
            self.graph.get_adjacency_matrix(normalize=True),
            dtype=torch.float32,
            requires_grad=False
        )
        self.register_buffer('A', A)

        # Number of adjacency matrix partitions
        spatial_kernel_size = A.size(0)  # 3 for spatial labeling

        # Temporal kernel size (odd numbers for symmetric padding)
        temporal_kernel_size = 9

        # Build ST-GCN layers
        kernel_size = (temporal_kernel_size, spatial_kernel_size)

        # Layer configurations: (in_channels, out_channels, stride)
        self.st_gcn_networks = nn.ModuleList((
            STGCNLayer(in_channels, 64, kernel_size, 1, dropout, residual=False),
            STGCNLayer(64, 64, kernel_size, 1, dropout),
            STGCNLayer(64, 64, kernel_size, 1, dropout),
            STGCNLayer(64, 64, kernel_size, 1, dropout),
            STGCNLayer(64, 128, kernel_size, 2, dropout),
            STGCNLayer(128, 128, kernel_size, 1, dropout),
            STGCNLayer(128, 128, kernel_size, 1, dropout),
            STGCNLayer(128, 256, kernel_size, 2, dropout),
            STGCNLayer(256, 256, kernel_size, 1, dropout),
            STGCNLayer(256, 256, kernel_size, 1, dropout),
        ))

        # Edge importance weighting
        if edge_importance_weighting:
            self.edge_importance = nn.ParameterList([
                nn.Parameter(torch.ones(self.A.size()))
                for _ in self.st_gcn_networks
            ])
        else:
            self.edge_importance = [1] * len(self.st_gcn_networks)

        # Fully connected layer for classification
        self.fcn = nn.Conv2d(256, num_classes, kernel_size=1)

    def forward(self, x):
        """
        Forward pass.

        Args:
            x: Input tensor (N, C, T, V, M)
                - N: Batch size
                - C: Number of channels (3)
                - T: Number of frames (60)
                - V: Number of joints (17)
                - M: Number of persons (1)

        Returns:
            Output logits (N, num_classes)
        """
        # Reshape input: (N, C, T, V, M) -> (N*M, C, T, V)
        N, C, T, V, M = x.size()
        x = x.permute(0, 4, 1, 2, 3).contiguous()  # (N, M, C, T, V)
        x = x.view(N * M, C, T, V)  # (N*M, C, T, V)

        # Forward through ST-GCN layers
        for gcn, importance in zip(self.st_gcn_networks, self.edge_importance):
            x = gcn(x, self.A * importance)

        # Global pooling: (N*M, C, T, V) -> (N*M, C)
        x = F.avg_pool2d(x, x.size()[2:])  # (N*M, C, 1, 1)
        x = x.view(N, M, -1, 1, 1).mean(dim=1)  # Average across persons: (N, C, 1, 1)

        # Classification
        x = self.fcn(x)  # (N, num_classes, 1, 1)
        x = x.view(x.size(0), -1)  # (N, num_classes)

        return x

    def extract_features(self, x):
        """
        Extract features before classification layer.

        Args:
            x: Input tensor (N, C, T, V, M)

        Returns:
            Feature tensor (N, 256)
        """
        # Reshape input
        N, C, T, V, M = x.size()
        x = x.permute(0, 4, 1, 2, 3).contiguous()
        x = x.view(N * M, C, T, V)

        # Forward through ST-GCN layers
        for gcn, importance in zip(self.st_gcn_networks, self.edge_importance):
            x = gcn(x, self.A * importance)

        # Global pooling
        x = F.avg_pool2d(x, x.size()[2:])
        x = x.view(N, M, -1).mean(dim=1)  # (N, 256)

        return x


def stgcn_binary(pretrained=False, **kwargs):
    """
    ST-GCN for binary fall detection (Fall vs Non-Fall).

    Args:
        pretrained: Whether to load pretrained weights (not implemented)
        **kwargs: Additional model arguments

    Returns:
        ST-GCN model
    """
    model = STGCN(num_classes=2, **kwargs)

    if pretrained:
        raise NotImplementedError("Pretrained weights not available")

    return model


def stgcn_multiclass(pretrained=False, **kwargs):
    """
    ST-GCN for multi-class fall detection (BY/FY/SY/N).

    Args:
        pretrained: Whether to load pretrained weights (not implemented)
        **kwargs: Additional model arguments

    Returns:
        ST-GCN model
    """
    model = STGCN(num_classes=4, **kwargs)

    if pretrained:
        raise NotImplementedError("Pretrained weights not available")

    return model


if __name__ == '__main__':
    # Test model construction
    print("Testing ST-GCN Model...")

    # Binary classification
    model_binary = stgcn_binary()
    print(f"\nBinary ST-GCN:")
    print(f"  Parameters: {sum(p.numel() for p in model_binary.parameters()):,}")
    print(f"  Trainable: {sum(p.numel() for p in model_binary.parameters() if p.requires_grad):,}")

    # Multi-class classification
    model_multiclass = stgcn_multiclass()
    print(f"\nMulti-class ST-GCN:")
    print(f"  Parameters: {sum(p.numel() for p in model_multiclass.parameters()):,}")

    # Test forward pass
    batch_size = 4
    input_tensor = torch.randn(batch_size, 3, 60, 17, 1)
    print(f"\nInput shape: {input_tensor.shape}")

    # Binary output
    output_binary = model_binary(input_tensor)
    print(f"Binary output shape: {output_binary.shape}")
    print(f"Binary output: {output_binary}")

    # Multi-class output
    output_multiclass = model_multiclass(input_tensor)
    print(f"Multi-class output shape: {output_multiclass.shape}")

    # Feature extraction
    features = model_binary.extract_features(input_tensor)
    print(f"Feature shape: {features.shape}")

    print("\nST-GCN model construction successful!")