python
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
'''
LEAF の 3 つの処理(ガボールフィルタ → 二乗 → ガウスの低域通過で間引く → sPCEN)の小さな実装。
式は原論文の式 (2)(4)(5)(6) に従う。初期値の決め方はこの実装での一例。
'''
def hz_to_mel(f):
return 2595.0 * math.log10(1.0 + f / 700.0)
def mel_to_hz(m):
return 700.0 * (10.0 ** (m / 2595.0) - 1.0)
class LEAF(nn.Module):
def __init__(self, n_filters=40, sample_rate=16000, window=401, stride=160):
super().__init__()
self.window, self.stride = window, stride
# 1. ガボールフィルタ:中心周波数 η(サンプリング周波数で割った値)と時間の幅 σ(サンプル)を学習
mels = torch.linspace(hz_to_mel(60.0), hz_to_mel(7800.0), n_filters)
self.eta = nn.Parameter(torch.tensor([mel_to_hz(m) for m in mels.tolist()]) / sample_rate)
self.sigma = nn.Parameter(torch.full((n_filters,), window / 8.0))
# 2. 間引きのガウスの幅(チャネルごと。t を -1〜1 に正規化した位置で表す)
self.lowpass_width = nn.Parameter(torch.full((n_filters,), 0.4))
# 3. sPCEN(この実装では PCEN の原論文の値と s = 0.04 で初期化)
self.log_alpha = nn.Parameter(torch.full((n_filters,), math.log(0.98)))
self.log_delta = nn.Parameter(torch.full((n_filters,), math.log(2.0)))
self.log_r = nn.Parameter(torch.full((n_filters,), math.log(0.5)))
self.s = nn.Parameter(torch.full((n_filters,), 0.04))
self.register_buffer('t', torch.arange(window, dtype=torch.float32) - (window - 1) / 2)
def gabor_kernels(self):
eta = self.eta.clamp(0.0, 0.5) # 中心周波数を正の範囲に収める
sigma = self.sigma.clamp(4 * math.sqrt(2 * math.log(2)), 2 * self.window * math.sqrt(2 * math.log(2)))
env = torch.exp(-self.t[None, :] ** 2 / (2 * sigma[:, None] ** 2)) / (math.sqrt(2 * math.pi) * sigma[:, None])
phase = 2 * math.pi * eta[:, None] * self.t[None, :]
# 実部と虚部を、隣り合う 2 本の実数のフィルタとして並べる
return torch.stack([env * torch.cos(phase), env * torch.sin(phase)], dim=1).reshape(-1, 1, self.window)
def forward(self, x):
# x: [バッチ, サンプル数]
n = self.eta.shape[0]
y = F.conv1d(x.unsqueeze(1), self.gabor_kernels(), padding=self.window // 2) # [B, 2N, T]
y = y.reshape(y.shape[0], n, 2, -1).pow(2).sum(dim=2) # 二乗の絶対値 [B, N, T]
# ガウスの低域通過フィルタをチャネルごとにかけて間引く(深さ方向の畳み込み)
tn = self.t / ((self.window - 1) / 2)
width = self.lowpass_width.clamp(2.0 / self.window, 0.5)
lp = torch.exp(-0.5 * (tn[None, :] / width[:, None]) ** 2)
lp = (lp / lp.sum(dim=1, keepdim=True)).unsqueeze(1) # [N, 1, W]
y = F.conv1d(y, lp, stride=self.stride, padding=self.window // 2, groups=n) # [B, N, フレーム数]
# sPCEN:平滑化の係数 s もチャネルごとに学習する
s = self.s.clamp(1e-3, 1.0)[None, :]
m, ms = y[..., 0], []
for t in range(y.shape[-1]):
m = (1 - s) * m + s * y[..., t]
ms.append(m)
m = torch.stack(ms, dim=-1)
alpha, delta, r = (p.exp()[None, :, None] for p in (self.log_alpha, self.log_delta, self.log_r))
return (y / (1e-6 + m) ** alpha + delta) ** r - delta ** r
frontend = LEAF(n_filters=40)
wave = torch.randn(4, 16000) # 1 秒の音を 4 本
features = frontend(wave)
print(features.shape) # torch.Size([4, 40, 100]) 40 チャネル・10 ms ごと(メルフィルタバンクと同じ並び)
# この後ろに EfficientNet などの分類モデルをつなぎ、フロントエンドごと学習する