時系列データ解析のための、ノイズに頑健なAutoencoder基盤のアーキテクチャを実装します。
基本実装
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from torch.utils.data import Dataset, DataLoader
from sklearn.preprocessing import StandardScaler
import torch.nn.functional as F
class TimeSeriesDataset(Dataset):
def __init__(self, features, targets, seq_len=50):
self.features = features
self.targets = targets
self.seq_len = seq_len
def __len__(self):
return len(self.features) - self.seq_len + 1
def __getitem__(self, idx):
return (
torch.FloatTensor(self.features[idx:idx+self.seq_len]),
torch.FloatTensor([self.targets[idx+self.seq_len-1]])
)
class NoiseRobustAutoencoder(nn.Module):
def __init__(self, input_dim=1000, hidden_dim=256, latent_dim=64,
noise_factor=0.1, dropout_rate=0.2):
super().__init__()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.latent_dim = latent_dim
self.noise_factor = noise_factor
# Encoder
self.encoder = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.BatchNorm1d(hidden_dim),
nn.ReLU(),
nn.Dropout(dropout_rate),
nn.Linear(hidden_dim, hidden_dim // 2),
nn.BatchNorm1d(hidden_dim // 2),
nn.ReLU(),
nn.Dropout(dropout_rate),
nn.Linear(hidden_dim // 2, latent_dim)
)
# Decoder
self.decoder = nn.Sequential(
nn.Linear(latent_dim, hidden_dim // 2),
nn.BatchNorm1d(hidden_dim // 2),
nn.ReLU(),
nn.Dropout(dropout_rate),
nn.Linear(hidden_dim // 2, hidden_dim),
nn.BatchNorm1d(hidden_dim),
nn.ReLU(),
nn.Dropout(dropout_rate),
nn.Linear(hidden_dim, input_dim)
)
# MLP for regression (encoded + original features)
self.mlp_regressor = nn.Sequential(
nn.Linear(latent_dim + input_dim, hidden_dim),
nn.BatchNorm1d(hidden_dim),
nn.ReLU(),
nn.Dropout(dropout_rate),
nn.Linear(hidden_dim, hidden_dim // 2),
nn.BatchNorm1d(hidden_dim // 2),
nn.ReLU(),
nn.Dropout(dropout_rate),
nn.Linear(hidden_dim // 2, 1)
)
# Decoder regression head
self.decoder_regressor = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.BatchNorm1d(hidden_dim),
nn.ReLU(),
nn.Dropout(dropout_rate),
nn.Linear(hidden_dim, 1)
)
def add_noise(self, x, training=True):
if training:
noise = torch.randn_like(x) * self.noise_factor
return x + noise
return x
def forward(self, x, training=True):
# 元の入力を保存
original_input = x.clone()
# ノイズを追加
x_noisy = self.add_noise(x, training)
# Encode
encoded = self.encoder(x_noisy)
# Decode
decoded = self.decoder(encoded)
# MLP route: encoded features + original input
mlp_input = torch.cat([encoded, original_input], dim=1)
mlp_output = self.mlp_regressor(mlp_input)
# Decoder route
decoder_output = self.decoder_regressor(decoded)
return {
'mlp_prediction': mlp_output,
'decoder_prediction': decoder_output,
'reconstruction': decoded,
'encoded': encoded
}
class RobustLoss(nn.Module):
def __init__(self, alpha=0.5, beta=0.3, gamma=0.2):
super().__init__()
self.alpha = alpha # MLP予測の重み
self.beta = beta # Decoder予測の重み
self.gamma = gamma # 再構成誤差の重み
def forward(self, outputs, targets, original_input):
# 回帰損失(Huber Lossでロバスト性向上)
mlp_loss = F.smooth_l1_loss(outputs['mlp_prediction'], targets)
decoder_loss = F.smooth_l1_loss(outputs['decoder_prediction'], targets)
# 再構成損失
reconstruction_loss = F.mse_loss(outputs['reconstruction'], original_input)
# 統合損失
total_loss = (self.alpha * mlp_loss +
self.beta * decoder_loss +
self.gamma * reconstruction_loss)
return {
'total_loss': total_loss,
'mlp_loss': mlp_loss,
'decoder_loss': decoder_loss,
'reconstruction_loss': reconstruction_loss
}
# 学習関数
def train_model(model, train_loader, val_loader, epochs=100, lr=1e-3):
optimizer = optim.Adam(model.parameters(), lr=lr)
scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience=10, factor=0.5)
criterion = RobustLoss()
best_val_loss = float('inf')
train_losses = []
val_losses = []
for epoch in range(epochs):
# Training
model.train()
train_loss = 0
for batch_x, batch_y in train_loader:
# 時系列の最後のタイムステップを使用
features = batch_x[:, -1, :]
optimizer.zero_grad()
outputs = model(features, training=True)
losses = criterion(outputs, batch_y, features)
losses['total_loss'].backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()
train_loss += losses['total_loss'].item()
# Validation
model.eval()
val_loss = 0
with torch.no_grad():
for batch_x, batch_y in val_loader:
features = batch_x[:, -1, :]
outputs = model(features, training=False)
losses = criterion(outputs, batch_y, features)
val_loss += losses['total_loss'].item()
avg_train_loss = train_loss / len(train_loader)
avg_val_loss = val_loss / len(val_loader)
train_losses.append(avg_train_loss)
val_losses.append(avg_val_loss)
scheduler.step(avg_val_loss)
if avg_val_loss < best_val_loss:
best_val_loss = avg_val_loss
torch.save(model.state_dict(), 'best_model.pth')
if epoch % 10 == 0:
print(f'Epoch {epoch}: Train Loss = {avg_train_loss:.4f}, Val Loss = {avg_val_loss:.4f}')
return train_losses, val_losses
# 推論関数
def predict(model, test_loader, ensemble=False):
model.eval()
predictions = []
with torch.no_grad():
for batch_x, _ in test_loader:
features = batch_x[:, -1, :]
if ensemble:
# アンサンブル予測(複数回の推論の平均)
ensemble_preds = []
for _ in range(5):
outputs = model(features, training=True) # ノイズありで複数回
pred = (outputs['mlp_prediction'] + outputs['decoder_prediction']) / 2
ensemble_preds.append(pred)
final_pred = torch.stack(ensemble_preds).mean(dim=0)
predictions.append(final_pred)
else:
outputs = model(features, training=False)
# MLPとDecoderの予測を組み合わせ
pred = (outputs['mlp_prediction'] + outputs['decoder_prediction']) / 2
predictions.append(pred)
return torch.cat(predictions, dim=0)
精度改善のためのカスタマイズ実装
1. Attention機構を追加したバージョン
class AttentionModule(nn.Module):
def __init__(self, input_dim):
super().__init__()
self.attention = nn.Sequential(
nn.Linear(input_dim, input_dim // 2),
nn.Tanh(),
nn.Linear(input_dim // 2, 1),
nn.Softmax(dim=1)
)
def forward(self, x):
weights = self.attention(x)
return x * weights
class ImprovedAutoencoder(NoiseRobustAutoencoder):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Attention層を追加
self.input_attention = AttentionModule(self.input_dim)
self.latent_attention = AttentionModule(self.latent_dim)
# 残差接続用の層
self.residual_transform = nn.Linear(self.input_dim, self.latent_dim)
def forward(self, x, training=True):
original_input = x.clone()
# 入力にAttentionを適用
x_attended = self.input_attention(x)
# ノイズを追加
x_noisy = self.add_noise(x_attended, training)
# Encode with residual
encoded = self.encoder(x_noisy)
residual = self.residual_transform(original_input)
encoded = encoded + residual
# Latent Attention
encoded = self.latent_attention(encoded)
# 以降は元の実装と同じ
decoded = self.decoder(encoded)
mlp_input = torch.cat([encoded, original_input], dim=1)
mlp_output = self.mlp_regressor(mlp_input)
decoder_output = self.decoder_regressor(decoded)
return {
'mlp_prediction': mlp_output,
'decoder_prediction': decoder_output,
'reconstruction': decoded,
'encoded': encoded
}
2. 時系列特化モデル(LSTM統合版)
class TemporalAutoencoder(nn.Module):
def __init__(self, input_dim=1000, hidden_dim=256, latent_dim=64,
lstm_hidden=128, num_layers=2, noise_factor=0.1):
super().__init__()
self.input_dim = input_dim
self.noise_factor = noise_factor
# LSTM for temporal encoding
self.lstm = nn.LSTM(
input_dim, lstm_hidden, num_layers,
batch_first=True, dropout=0.2, bidirectional=True
)
# Standard encoder (LSTM出力を入力として使用)
self.encoder = nn.Sequential(
nn.Linear(lstm_hidden * 2, hidden_dim),
nn.BatchNorm1d(hidden_dim),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(hidden_dim, latent_dim)
)
# Decoder
self.decoder = nn.Sequential(
nn.Linear(latent_dim, hidden_dim),
nn.BatchNorm1d(hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, input_dim)
)
# Regression heads
self.mlp_regressor = nn.Sequential(
nn.Linear(latent_dim + lstm_hidden * 2, hidden_dim),
nn.BatchNorm1d(hidden_dim),
nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(hidden_dim, 1)
)
self.decoder_regressor = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, 1)
)
def forward(self, x, training=True):
# x shape: (batch, seq_len, features)
batch_size = x.size(0)
# ノイズを追加
if training:
noise = torch.randn_like(x) * self.noise_factor
x_noisy = x + noise
else:
x_noisy = x
# LSTM encoding
lstm_out, _ = self.lstm(x_noisy)
lstm_features = lstm_out[:, -1, :] # 最後のタイムステップ
# Standard encoding
encoded = self.encoder(lstm_features)
# Decode
decoded = self.decoder(encoded)
# Predictions
mlp_input = torch.cat([encoded, lstm_features], dim=1)
mlp_output = self.mlp_regressor(mlp_input)
decoder_output = self.decoder_regressor(decoded)
return {
'mlp_prediction': mlp_output,
'decoder_prediction': decoder_output,
'reconstruction': decoded,
'encoded': encoded
}
3. データ拡張と前処理の改善
class DataAugmentation:
def __init__(self, noise_levels=[0.05, 0.1, 0.15],
shift_range=0.1, scale_range=0.1):
self.noise_levels = noise_levels
self.shift_range = shift_range
self.scale_range = scale_range
def augment(self, x, y):
augmented_x = []
augmented_y = []
# Original data
augmented_x.append(x)
augmented_y.append(y)
# Noise augmentation
for noise_level in self.noise_levels:
noise = np.random.normal(0, noise_level, x.shape)
augmented_x.append(x + noise)
augmented_y.append(y)
# Time shift augmentation
shift = int(x.shape[0] * self.shift_range)
if shift > 0:
# Forward shift
x_shift = np.roll(x, shift, axis=0)
augmented_x.append(x_shift)
augmented_y.append(y)
# Backward shift
x_shift = np.roll(x, -shift, axis=0)
augmented_x.append(x_shift)
augmented_y.append(y)
# Scaling augmentation
scale = 1 + np.random.uniform(-self.scale_range, self.scale_range)
augmented_x.append(x * scale)
augmented_y.append(y)
return np.vstack(augmented_x), np.hstack(augmented_y)
# 特徴量の前処理
class FeatureEngineering:
def __init__(self, n_components=50):
self.n_components = n_components
self.scaler = StandardScaler()
self.pca = None
def fit_transform(self, X):
# 標準化
X_scaled = self.scaler.fit_transform(X)
# 移動平均特徴量
window_sizes = [5, 10, 20]
ma_features = []
for w in window_sizes:
ma = np.convolve(X_scaled.mean(axis=1),
np.ones(w)/w, mode='same')
ma_features.append(ma.reshape(-1, 1))
# 差分特徴量
diff_features = np.diff(X_scaled, axis=0, prepend=X_scaled[0:1])
# 結合
X_enhanced = np.hstack([X_scaled, *ma_features, diff_features])
return X_enhanced
4. 使用例とトレーニングスクリプト
# データ準備
def prepare_data(features, targets, test_size=0.2, seq_len=50):
# データ拡張
augmenter = DataAugmentation()
features_aug, targets_aug = augmenter.augment(features, targets)
# 特徴量エンジニアリング
fe = FeatureEngineering()
features_enhanced = fe.fit_transform(features_aug)
# Train/Val/Test分割
n_samples = len(features_enhanced)
train_size = int(n_samples * 0.7)
val_size = int(n_samples * 0.15)
train_features = features_enhanced[:train_size]
train_targets = targets_aug[:train_size]
val_features = features_enhanced[train_size:train_size+val_size]
val_targets = targets_aug[train_size:train_size+val_size]
test_features = features_enhanced[train_size+val_size:]
test_targets = targets_aug[train_size+val_size:]
# データセット作成
train_dataset = TimeSeriesDataset(train_features, train_targets, seq_len)
val_dataset = TimeSeriesDataset(val_features, val_targets, seq_len)
test_dataset = TimeSeriesDataset(test_features, test_targets, seq_len)
# DataLoader
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=32, shuffle=False)
test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)
return train_loader, val_loader, test_loader
# メイントレーニング
def main():
# ダミーデータ生成(実際のデータに置き換える)
np.random.seed(42)
n_samples = 10000
n_features = 1000
# 低相関の特徴量を生成
features = np.random.randn(n_samples, n_features)
targets = np.random.randn(n_samples) * 0.1 + features.mean(axis=1) * 0.06
# データ準備
train_loader, val_loader, test_loader = prepare_data(features, targets)
# モデル選択(改善版を使用)
model = ImprovedAutoencoder(
input_dim=features.shape[1],
hidden_dim=512,
latent_dim=128,
noise_factor=0.15,
dropout_rate=0.3
)
# 学習
train_losses, val_losses = train_model(
model, train_loader, val_loader,
epochs=200, lr=5e-4
)
# 最良モデルをロード
model.load_state_dict(torch.load('best_model.pth'))
# テスト予測(アンサンブル使用)
predictions = predict(model, test_loader, ensemble=True)
return model, predictions
if __name__ == "__main__":
model, predictions = main()
このアーキテクチャの特徴:
- ノイズ頑健性: Gaussian Noiseの追加、Dropout、Huber Lossの使用
- マルチパス学習: MLPルートとDecoderルートの組み合わせ
- 改善案の実装:
- Attention機構による重要特徴の選択
- 残差接続による勾配消失の防止
- LSTM統合による時系列パターンの学習
- データ拡張による汎化性能の向上
- アンサンブル推論によるロバスト性向上
低相関データに対しては、複数の視点から特徴を抽出し、ノイズに対する頑健性を高めることが重要です。