以下に、Autoencoderをベースとした時系列回帰モデルの実装例と、精度改善のためのカスタマイズ案を提供します。PyTorchを用いた実装を想定しています。
モデルアーキテクチャの実装
import torch
import torch.nn as nn
import torch.optim as optim
class TimeSeriesAE(nn.Module):
def __init__(self, input_dim=1000, hidden_dim=256, noise_std=0.1):
super().__init__()
self.noise = nn.Dropout(p=noise_std) # GaussianNoiseの代わりにDropoutを使用
self.encoder = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, hidden_dim//2)
)
self.decoder = nn.Sequential(
nn.Linear(hidden_dim//2, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, input_dim)
)
self.mlp_head = nn.Sequential(
nn.Linear(hidden_dim//2 + input_dim, 128),
nn.ReLU(),
nn.Linear(128, 1)
)
self.regressor_head = nn.Linear(input_dim, 1) # デコーダ出力からターゲット推論
def forward(self, x):
# 入力にノイズを加える
x_noisy = self.noise(x)
# エンコード
encoded = self.encoder(x_noisy)
# デコードルート
decoded = self.decoder(encoded)
regressor_out = self.regressor_head(decoded)
# MLPルート(エンコード前と後の特徴量を結合)
combined = torch.cat([encoded, x], dim=1)
mlp_out = self.mlp_head(combined)
return decoded, regressor_out, mlp_out
# モデル、損失関数、最適化手法の設定
model = TimeSeriesAE(input_dim=1000)
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=1e-3)
学習コード
def train(model, train_loader, val_loader, epochs=100):
model.train()
best_loss = float('inf')
for epoch in range(epochs):
for batch in train_loader:
x, y = batch['features'], batch['target']
decoded, regressor_out, mlp_out = model(x)
# 損失の計算(再構成損失 + 回帰損失)
recon_loss = criterion(decoded, x)
regressor_loss = criterion(regressor_out, y.view(-1,1))
mlp_loss = criterion(mlp_out, y.view(-1,1))
total_loss = recon_loss + regressor_loss + mlp_loss # 重み調整が必要
optimizer.zero_grad()
total_loss.backward()
optimizer.step()
# バリデーション
model.eval()
with torch.no_grad():
val_recon_loss = 0
val_regressor_loss = 0
val_mlp_loss = 0
for batch in val_loader:
x_val, y_val = batch['features'], batch['target']
decoded_val, regressor_out_val, mlp_out_val = model(x_val)
val_recon_loss += criterion(decoded_val, x_val).item()
val_regressor_loss += criterion(regressor_out_val, y_val.view(-1,1)).item()
val_mlp_loss += criterion(mlp_out_val, y_val.view(-1,1)).item()
avg_loss = val_recon_loss + val_regressor_loss + val_mlp_loss
if avg_loss < best_loss:
best_loss = avg_loss
torch.save(model.state_dict(), 'best_model.pth')
model.train()
推論コード
def inference(model, test_loader):
model.load_state_dict(torch.load('best_model.pth'))
model.eval()
predictions = []
with torch.no_grad():
for batch in test_loader:
x = batch['features']
_, regressor_out, mlp_out = model(x)
# 両ルートの出力を平均で予測
pred = (regressor_out + mlp_out) / 2
predictions.append(pred.numpy())
return np.concatenate(predictions)
精度改善のためのカスタマイズ案
1. ドロップアウトとバッチノーマライゼーションの追加
class ImprovedTimeSeriesAE(TimeSeriesAE):
def __init__(self):
super().__init__()
self.encoder = nn.Sequential(
nn.Linear(1000, 256),
nn.BatchNorm1d(256),
nn.Dropout(0.2),
nn.ReLU(),
nn.Linear(256, 128),
nn.BatchNorm1d(128),
nn.Dropout(0.2)
)
self.decoder = nn.Sequential(
nn.Linear(128, 256),
nn.BatchNorm1d(256),
nn.Dropout(0.2),
nn.ReLU(),
nn.Linear(256, 1000)
)
self.mlp_head = nn.Sequential(
nn.Linear(128 + 1000, 256),
nn.BatchNorm1d(256),
nn.Dropout(0.3),
nn.ReLU(),
nn.Linear(256, 1)
)
2. 注意(Attention)層の導入
class AttentionLayer(nn.Module):
def __init__(self, input_dim):
super().__init__()
self.query = nn.Linear(input_dim, input_dim)
self.key = nn.Linear(input_dim, input_dim)
self.value = nn.Linear(input_dim, input_dim)
def forward(self, x):
Q = self.query(x)
K = self.key(x)
V = self.value(x)
attention = torch.softmax(Q @ K.T / (x.shape[1]**0.5), dim=-1)
return attention @ V
class AttentionAE(TimeSeriesAE):
def __init__(self):
super().__init__()
self.attention = AttentionLayer(128)
def forward(self, x):
encoded = self.encoder(x)
encoded = self.attention(encoded) # 注意層を追加
decoded = self.decoder(encoded)
# 以降は同様
3. モデル平均化(Model Averaging)
# 学習後に複数エポックのモデルを平均化
models = [TimeSeriesAE() for _ in range(5)]
for model in models:
model.load_state_dict(torch.load(f'model_epoch_{i}.pth'))
def averaged_inference(models, test_loader):
predictions = []
for model in models:
_, regressor_out, mlp_out = model(x)
predictions.append((regressor_out + mlp_out)/2)
return torch.mean(torch.stack(predictions), dim=0)
4. 損失関数の調整(Huber Loss)
criterion = nn.HuberLoss(delta=1.0) # ノイズに強い損失関数
5. データ拡張(時系列のシフト)
class TimeSeriesDataset(torch.utils.data.Dataset):
def __init__(self, data, target, shift_range=5):
self.data = data
self.target = target
self.shift_range = shift_range
def __getitem__(self, idx):
x = self.data[idx].copy()
shift = np.random.randint(-self.shift_range, self.shift_range)
x = np.roll(x, shift) # 時系列のシフト
return {'features': x, 'target': self.target[idx]}
実装上の注意点
-
ハイパーパラメータ調整
noise_std: 0.1~0.3で調整(ノイズの強さ)
hidden_dim: 入力次元の半分程度から開始
batch_size: GPUメモリに合わせて調整(例: 32~256)
-
モデルの初期化
nn.init.kaiming_uniform_ で重みを初期化する。
-
学習率スケジューラー
scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', patience=5)
-
Early Stopping
バリデーション損失が改善しなくなった時点で学習を終了。
コードの改良提案
-
残差接続(Residual Connection)
エンコーダー/デコーダーに残差ブロックを追加することで、深層学習の勾配消失を防ぐ。
-
時系列の位置情報考慮
入力に位置エンコーディング(Positional Encoding)を追加し、時系列の順序を考慮。
-
LightGBMとのハイブリッドモデル
Autoencoderの特徴量をLightGBMの入力に追加してアンサンブル。
このアプローチは、ノイズに強いモデルを構築しつつ、低い相関の特徴量からパターンを抽出する設計です。実際のデータに合わせてハイパーパラメータを調整し、カスタマイズ案を組み合わせることで、精度向上が期待できます。