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
| import torch import torch.nn as nn import torch.nn.functional as F
class EdgeConv(nn.Module): """ EdgeConv层 - DGCNN的核心操作 对每个点的k近邻计算边特征,再通过MLP聚合 """ def __init__(self, in_channels: int, out_channels: int, k: int = 16): super().__init__() self.k = k self.mlp = nn.Sequential( nn.Linear(in_channels * 2, out_channels), nn.BatchNorm1d(out_channels), nn.LeakyReLU(0.2), nn.Linear(out_channels, out_channels), ) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: 点云数据, shape=(B, N, C) B=batch_size, N=点数, C=特征维度 Returns: out: 变换后的特征, shape=(B, N, out_channels) """ B, N, C = x.shape dist_matrix = torch.cdist(x, x) _, knn_idx = torch.topk(-dist_matrix, self.k, dim=-1) knn_features = torch.gather( x.unsqueeze(2).expand(-1, -1, self.k, -1), 1, knn_idx.unsqueeze(-1).expand(-1, -1, -1, C) ) center_feature = x.unsqueeze(2).expand(-1, -1, self.k, -1) edge_feature = torch.cat([ center_feature, knn_features - center_feature ], dim=-1) edge_features = self.mlp(edge_features.reshape(B * N * self.k, -1)) edge_features = edge_features.reshape(B, N, self.k, -1) out = edge_features.max(dim=2)[0] return out
class DGCNNFeatureExtractor(nn.Module): """ DGCNN空间特征提取器 用于mmWave雷达点云的空间结构特征提取 """ def __init__(self, input_dim: int = 3, hidden_dim: int = 64, k: int = 16): super().__init__() self.edge1 = EdgeConv(input_dim, hidden_dim, k) self.edge2 = EdgeConv(hidden_dim, hidden_dim * 2, k) self.edge3 = EdgeConv(hidden_dim * 2, hidden_dim * 4, k) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: 点云序列, shape=(B, N, 3) Returns: features: 空间特征, shape=(B, N, 256) """ x1 = self.edge1(x) x2 = self.edge2(x1) x3 = self.edge3(x2) return x3
|