python コピー
import torch
import torch.nn as nn
import torch.nn.functional as F
class DropConnectLinear(nn.Module):
"""論文の DropConnect の層:r = a((M ⋆ W) v)。活性化関数 a も層の中に含める。
keep_prob は重みを「残す」確率 p(論文と同じ向き。PyTorch の Dropout の p とは逆)。
"""
def __init__(self, in_features, out_features, keep_prob=0.5, num_samples=1000):
super().__init__()
self.linear = nn.Linear(in_features, out_features)
self.p = keep_prob
self.num_samples = num_samples # 推論時に正規分布から引く数 Z
def forward(self, v): # v: (バッチ, 入力の数)
W, b = self.linear.weight, self.linear.bias # W: (出力の数, 入力の数)
if self.training:
# 学習時:重みとバイアスのマスクを、データ 1 件ごとに作る
M = torch.bernoulli(torch.full((v.size(0), *W.shape), self.p, device=v.device))
m_b = torch.bernoulli(torch.full((v.size(0), b.numel()), self.p, device=v.device))
u = torch.einsum("bdn,bn->bd", M * W, v) + m_b * b
return F.relu(u)
# 推論時:u を正規分布で近似し(モーメントマッチング)、Z 回引いて a(u) を平均する
mean = self.p * (v @ W.t() + b) # E[u] = pWv
var = self.p * (1 - self.p) * ((v ** 2) @ (W ** 2).t() + b ** 2) # V[u] = p(1−p)(W⋆W)(v⋆v)
eps = torch.randn(self.num_samples, *mean.shape, device=v.device)
u = mean + var.sqrt() * eps
return F.relu(u).mean(dim=0)
# 畳み込み層で特徴を取り出し、DropConnect の全結合層、ソフトマックス層(落とさない)と続けるモデル
class Net(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(1, 32, 5), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(32, 64, 5), nn.ReLU(), nn.MaxPool2d(2),
nn.Flatten(),
)
self.dropconnect = DropConnectLinear(64 * 4 * 4, 150, keep_prob=0.5)
self.classifier = nn.Linear(150, num_classes)
def forward(self, x):
return self.classifier(self.dropconnect(self.features(x)))
model = Net()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
criterion = nn.CrossEntropyLoss()
# 学習:model.train() で、重みをランダムに落とす
model.train()
images = torch.randn(32, 1, 28, 28) # MNIST を想定したダミーのミニバッチ
labels = torch.randint(0, 10, (32,))
loss = criterion(model(images), labels)
optimizer.zero_grad()
loss.backward() # 落とした重みの勾配は 0 になり、使った重みだけが更新される
optimizer.step()
# 推論:model.eval() で、正規分布のサンプリングによる推論に切り替える
model.eval()
with torch.no_grad():
predicted = model(images).argmax(dim=1)