python
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
PointNet の分類のネットワーク(論文の Figure 2・付録 C)の小さな実装。
共有の MLP はカーネル 1 の Conv1d で書く(すべての点に同じ全結合層をかけるのと同じ)。
"""
def shared_mlp(sizes):
layers = []
for c_in, c_out in zip(sizes[:-1], sizes[1:]):
layers += [nn.Conv1d(c_in, c_out, 1), nn.BatchNorm1d(c_out), nn.ReLU()]
return nn.Sequential(*layers)
class TNet(nn.Module):
"""k×k の変換行列を予測する小さな PointNet。出力は単位行列から始まる"""
def __init__(self, k):
super().__init__()
self.k = k
self.mlp = shared_mlp([k, 64, 128, 1024])
self.fc = nn.Sequential(nn.Linear(1024, 512), nn.BatchNorm1d(512), nn.ReLU(),
nn.Linear(512, 256), nn.BatchNorm1d(256), nn.ReLU(),
nn.Linear(256, k * k))
nn.init.zeros_(self.fc[-1].weight)
nn.init.zeros_(self.fc[-1].bias) # 最初は単位行列 + 0
def forward(self, x): # x:[B, k, n]
g = self.mlp(x).max(dim=2).values # 点の方向に最大値 → [B, 1024]
eye = torch.eye(self.k, device=x.device).flatten()
return (self.fc(g) + eye).view(-1, self.k, self.k) # [B, k, k]
class PointNetCls(nn.Module):
def __init__(self, num_classes=40):
super().__init__()
self.input_tnet = TNet(3) # 入力の変換 3×3
self.mlp1 = shared_mlp([3, 64, 64])
self.feature_tnet = TNet(64) # 特徴の変換 64×64
self.mlp2 = shared_mlp([64, 64, 128, 1024])
self.head = nn.Sequential(nn.Linear(1024, 512), nn.BatchNorm1d(512), nn.ReLU(),
nn.Linear(512, 256), nn.BatchNorm1d(256), nn.ReLU(),
nn.Dropout(p=0.3), # 残す割合 0.7
nn.Linear(256, num_classes))
def forward(self, pts): # pts:[B, n, 3](並び順は自由)
x = pts.transpose(1, 2) # [B, 3, n]
T1 = self.input_tnet(x)
x = torch.bmm(T1, x) # 座標に 3×3 の行列を掛ける
x = self.mlp1(x) # [B, 64, n]
A = self.feature_tnet(x)
x = torch.bmm(A, x) # 特徴に 64×64 の行列を掛ける
x = self.mlp2(x) # [B, 1024, n]
g = x.max(dim=2).values # 対称な関数:点の方向に最大値
return self.head(g), A
def orthogonal_reg(A):
"""式 (2):L_reg = ||I - A A^T||_F^2"""
eye = torch.eye(A.shape[1], device=A.device)
return ((eye - torch.bmm(A, A.transpose(1, 2))) ** 2).sum(dim=(1, 2)).mean()
model = PointNetCls(num_classes=40)
model.train() # Dropout と BatchNorm は train と eval で挙動が変わる
pts = torch.randn(8, 1024, 3)
labels = torch.randint(0, 40, (8,))
logits, A = model(pts)
loss = F.cross_entropy(logits, labels) + 0.001 * orthogonal_reg(A)
loss.backward()
model.eval() # 推論:Dropout を止め、BatchNorm は移動平均を使う
with torch.no_grad():
perm = torch.randperm(1024)
out1, _ = model(pts)
out2, _ = model(pts[:, perm]) # 点の順番を入れ替えても
print(torch.allclose(out1, out2, atol=1e-5)) # True:同じ出力になる