python コピー
import torch
import torch.nn as nn
"""
Deep Speech 2 の形(2D 畳み込み → 系列ごとのバッチ正規化つきの双方向 RNN → 全結合 → CTC)を小さく実装する例。
論文の式 (8):h_t = f(B(W x_t) + U h_{t-1})。バッチ正規化は入力からの項だけにかけ、前向きと後ろ向きで W を共有する。
PyTorch の nn.CTCLoss は、log_softmax をかけた (時刻, バッチ, クラス) の値を受け取る。blank の既定は 0。
"""
def clipped_relu(x):
return torch.clamp(x, min=0.0, max=20.0) # min(max(x, 0), 20)
class BNBiRNN(nn.Module):
def __init__(self, n_in, hidden):
super().__init__()
self.W = nn.Linear(n_in, hidden, bias=False) # 前向き・後ろ向きで共有。バイアスは正規化で消えるので外す
self.bn = nn.BatchNorm1d(hidden) # 系列ごと:バッチと全時刻で平均・分散を取る
self.U_f = nn.Linear(hidden, hidden, bias=False)
self.U_b = nn.Linear(hidden, hidden, bias=False)
def forward(self, x): # x: [B, T, n_in]
wx = self.bn(self.W(x).transpose(1, 2)).transpose(1, 2) # B(W x_t)
B, T, H = wx.shape
h_f, h_b = wx.new_zeros(B, H), wx.new_zeros(B, H)
out_f, out_b = [], []
for t in range(T): # 前向き
h_f = clipped_relu(wx[:, t] + self.U_f(h_f))
out_f.append(h_f)
for t in reversed(range(T)): # 後ろ向き
h_b = clipped_relu(wx[:, t] + self.U_b(h_b))
out_b.append(h_b)
return torch.stack(out_f, 1) + torch.stack(out_b[::-1], 1) # 2 方向を足す
class DeepSpeech2(nn.Module):
def __init__(self, n_freq=161, n_classes=29, hidden=512, n_rnn=3):
super().__init__()
# 2D 畳み込み(周波数 × 時間)。最初の層で時間を 2 分の 1 に間引く
self.conv = nn.Sequential(
nn.Conv2d(1, 32, (41, 11), stride=(2, 2), padding=(20, 5)), nn.BatchNorm2d(32), nn.Hardtanh(0, 20),
nn.Conv2d(32, 32, (21, 11), stride=(2, 1), padding=(10, 5)), nn.BatchNorm2d(32), nn.Hardtanh(0, 20))
f = (n_freq + 1) // 2
f = (f + 1) // 2
self.rnns = nn.ModuleList([BNBiRNN(32 * f if i == 0 else hidden, hidden) for i in range(n_rnn)])
self.fc = nn.Linear(hidden, n_classes) # 文字 + 空白(番号 0)
def forward(self, spec): # spec: [B, 周波数, 時間]
h = self.conv(spec.unsqueeze(1)) # [B, 32, F', T']
h = h.permute(0, 3, 1, 2).flatten(2) # [B, T', 32*F']
for rnn in self.rnns:
h = rnn(h)
return self.fc(h).log_softmax(-1) # [B, T', クラス]
model = DeepSpeech2()
spec = torch.randn(4, 161, 300) # 3 秒分のスペクトログラム
targets = torch.randint(1, 29, (4, 40)) # 正解の文字(0 は空白)
target_lengths = torch.tensor([40, 35, 30, 25])
model.train() # バッチ正規化はミニバッチの統計を使う
log_probs = model(spec)
input_lengths = torch.full((4,), log_probs.size(1), dtype=torch.long)
ctc = nn.CTCLoss(blank=0, zero_infinity=True)
loss = ctc(log_probs.transpose(0, 1), targets, input_lengths, target_lengths) # (T, B, C) で渡す
loss.backward()
model.eval() # 推論では学習中に集めた平均・分散を使う
class RowConv(nn.Module):
"""行の畳み込み(式 (11)):r_{t,i} = Σ_{j=1}^{τ+1} W_{i,j} h_{t+j-1,i}。前向きだけの RNN の上に置く"""
def __init__(self, d, tau=19):
super().__init__()
self.tau = tau
self.conv = nn.Conv1d(d, d, tau + 1, groups=d, bias=False) # 次元ごとに別の重み
def forward(self, h): # h: [B, T, d]
h = nn.functional.pad(h.transpose(1, 2), (0, self.tau)) # 先の τ 時刻ぶんだけ見る(末尾を 0 で埋める)
return self.conv(h).transpose(1, 2) # [B, T, d]