import torch import torch.nn as nn import torch.nn.functional as F from…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
def torch_log(x): return torch.log(torch.clamp(x, min=1e-10))
class AdvancedSequenceTaggingNet(nn.Module): def init(self, vocab_size, emb_dim, hid_dim, num_layers=2, dropout_rate=0.3, bidirectional=True): """ 改善点を盛り込んだ高機能なシーケンス分類モデル
Args:
vocab_size (int): 語彙数
emb_dim (int): 埋め込みベクトルの次元数
hid_dim (int): LSTMの隠れ層の次元数
num_layers (int): LSTMの層数
dropout_rate (float): ドロップアウト率
bidirectional (bool): 双方向LSTMを使用するかどうか
"""
super().__init__()
# 1. 標準のnn.Embeddingを使用
self.emb = nn.Embedding(vocab_size, emb_dim, padding_idx=0) # padding_idx=0を指定(一般的)
# 2. LSTMの改善
self.lstm = nn.LSTM(
input_size=emb_dim,
hidden_size=hid_dim,
num_layers=num_layers, # 3. LSTMの多層化
batch_first=True,
bidirectional=bidirectional, # 4. 双方向LSTM
dropout=dropout_rate if num_layers > 1 else 0 # 層間のドロップアウト
)
# 5. ドロップアウト層を追加
self.dropout = nn.Dropout(dropout_rate)
# 双方向の場合、最後の線形層への入力次元は2倍になる
linear_input_dim = hid_dim * 2 if bidirectional else hid_dim
self.linear = nn.Linear(linear_input_dim, 1)
def forward(self, x, seq_lengths):
"""
Args:
x (Tensor): 入力テンソル (batch_size, seq_len)
seq_lengths (Tensor): 各シーケンスの実際の長さ (batch_size,)
"""
# (batch_size, seq_len) -> (batch_size, seq_len, emb_dim)
h = self.emb(x)
h = self.dropout(h) # Embedding後のDropout
# 6. 可変長シーケンスの効率的な処理 (pack_padded_sequence)
# これにより、padding部分の無駄な計算を省略し、正しい最終隠れ状態を取得できる
packed_h = pack_padded_sequence(h, seq_lengths.cpu(), batch_first=True, enforce_sorted=False)
# LSTMに入力
# outputは全タイムステップの隠れ状態、(h_n, c_n)は最終タイムステップの隠れ状態とセル状態
packed_output, (h_n, c_n) = self.lstm(packed_h)
# (任意) 全タイムステップの隠れ状態を使いたい場合はpad_packed_sequenceで元に戻す
# output, _ = pad_packed_sequence(packed_output, batch_first=True)
# 7. 最終隠れ状態のスマートな取得
# h_n の形状: (num_layers * num_directions, batch_size, hid_dim)
if self.lstm.bidirectional:
# 前方向の最終層の隠れ状態と、後ろ方向の最終層の隠れ状態を連結
# h_n[-2,:,:] はフォワードの最終層、h_n[-1,:,:] はバックワードの最終層
h_n_combined = torch.cat((h_n[-2,:,:], h_n[-1,:,:]), dim=1)
else:
# 片方向の場合は、最後の層の隠れ状態をそのまま使う
h_n_combined = h_n[-1,:,:]
h_n_combined = self.dropout(h_n_combined)
y = self.linear(h_n_combined)
return y.squeeze(1) # 出力サイズを (batch_size, 1) -> (batch_size,) にする
このモデルの改善点はありますか?
現在のモデルは既に多くの優れた機能を備えていますが、さらに以下の改善点が考えられます:
Attention機構の導入:
class SelfAttention(nn.Module):
def __init__(self, hidden_dim):
super().__init__()
self.query = nn.Linear(hidden_dim, hidden_dim)
self.key = nn.Linear(hidden_dim, hidden_dim)
self.value = nn.Linear(hidden_dim, hidden_dim)
self.scale = torch.sqrt(torch.FloatTensor([hidden_dim]))
def forward(self, hidden):
# hidden: (batch_size, seq_len, hidden_dim)
Q = self.query(hidden)
K = self.key(hidden)
V = self.value(hidden)
# (batch_size, seq_len, seq_len)
attention = torch.matmul(Q, K.permute(0, 2, 1)) / self.scale
# (batch_size, seq_len, hidden_dim)
weighted = torch.matmul(F.softmax(attention, dim=-1), V)
return weighted, attention
CRFレイヤーの追加(シーケンスタギングの場合に効果的):
class CRF(nn.Module):
def __init__(self, num_tags):
super().__init__()
self.num_tags = num_tags
self.transitions = nn.Parameter(torch.randn(num_tags, num_tags))
def forward(self, emissions, tags, mask=None):
# CRFの実装...
pass
Layer Normalizationの追加:
self.layer_norm = nn.LayerNorm(hid_dim * 2 if bidirectional else hid_dim)
# forward内で使用
h_n_combined = self.layer_norm(h_n_combined)
残差接続の追加(多層LSTMの場合)
文字レベル特徴の統合:
self.char_emb = nn.Embedding(char_vocab_size, char_emb_dim)
self.char_lstm = nn.LSTM(char_emb_dim, char_hid_dim, batch_first=True, bidirectional=True)
# Embeddingと文字レベル特徴を結合
word_emb = self.emb(x)
char_features = self.process_chars(char_x) # 別途実装
combined_emb = torch.cat((word_emb, char_features), dim=-1)
事前学習済み言語モデルとの統合(BERTなど)
マルチタスク学習のサポート(複数の出力ヘッド)
混合精度トレーニングのサポート(計算効率向上)
Focal Lossなどの高度な損失関数の導入(クラス不均衡問題対策)
学習率スケジューラーの統合
これらの改善点を状況やタスクに応じて取り入れることで、モデルの性能をさらに向上させることができるでしょう。
コードを説明または詳しく解説しましょうか?
attentionを追加してください.
こちらが Attention 機構を追加した AdvancedSequenceTaggingNet モデルです:
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
def torch_log(x):
return torch.log(torch.clamp(x, min=1e-10))
# Attention機構の実装
class Attention(nn.Module):
def __init__(self, hidden_dim):
super().__init__()
self.hidden_dim = hidden_dim
self.attention = nn.Linear(hidden_dim, 1)
def forward(self, lstm_output, mask=None):
"""
Args:
lstm_output: LSTMの全時間ステップの出力 (batch_size, seq_len, hidden_dim)
mask: 有効な位置を示すマスク (batch_size, seq_len)
Returns:
context_vector: 注目された文脈ベクトル (batch_size, hidden_dim)
attention_weights: 注目の重み (batch_size, seq_len)
"""
# attention_weights: (batch_size, seq_len, 1)
attention_weights = self.attention(lstm_output)
# (batch_size, seq_len)
attention_weights = attention_weights.squeeze(2)
# マスクがある場合は、パディング部分の重みを非常に小さい値に設定
if mask is not None:
attention_weights = attention_weights.masked_fill(mask == 0, -1e10)
# softmaxで正規化して確率分布に変換
attention_weights = F.softmax(attention_weights, dim=1)
# 重み付き和を計算して文脈ベクトルを取得
# (batch_size, 1, seq_len) * (batch_size, seq_len, hidden_dim) -> (batch_size, 1, hidden_dim)
context_vector = torch.bmm(attention_weights.unsqueeze(1), lstm_output)
# (batch_size, hidden_dim)
context_vector = context_vector.squeeze(1)
return context_vector, attention_weights
# 改善版シーケンスタギングモデル(Attention追加)
class AdvancedSequenceTaggingNet(nn.Module):
def __init__(self, vocab_size, emb_dim, hid_dim, num_layers=2, dropout_rate=0.3, bidirectional=True):
"""
Attention機構を追加した高機能なシーケンス分類モデル
Args:
vocab_size (int): 語彙数
emb_dim (int): 埋め込みベクトルの次元数
hid_dim (int): LSTMの隠れ層の次元数
num_layers (int): LSTMの層数
dropout_rate (float): ドロップアウト率
bidirectional (bool): 双方向LSTMを使用するかどうか
"""
super().__init__()
# 1. 標準のnn.Embeddingを使用
self.emb = nn.Embedding(vocab_size, emb_dim, padding_idx=0)
# 2. LSTMの改善
self.lstm = nn.LSTM(
input_size=emb_dim,
hidden_size=hid_dim,
num_layers=num_layers,
batch_first=True,
bidirectional=bidirectional,
dropout=dropout_rate if num_layers > 1 else 0
)
# 5. ドロップアウト層を追加
self.dropout = nn.Dropout(dropout_rate)
# 双方向の場合、hidden_dimは2倍になる
self.lstm_output_dim = hid_dim * 2 if bidirectional else hid_dim
# Attention機構の追加
self.attention = Attention(self.lstm_output_dim)
# 出力層
self.linear = nn.Linear(self.lstm_output_dim, 1)
def forward(self, x, seq_lengths):
"""
Args:
x (Tensor): 入力テンソル (batch_size, seq_len)
seq_lengths (Tensor): 各シーケンスの実際の長さ (batch_size,)
"""
# Embeddingと初期のドロップアウト
h = self.emb(x)
h = self.dropout(h)
# パックしてLSTMに入力
packed_h = pack_padded_sequence(h, seq_lengths.cpu(), batch_first=True, enforce_sorted=False)
packed_output, (h_n, c_n) = self.lstm(packed_h)
# パックされた出力をアンパックする(Attentionに使用するため)
lstm_output, output_lengths = pad_packed_sequence(packed_output, batch_first=True)
# マスクの作成(有効な位置を1、パディングを0とする)
batch_size, max_len = x.size()
mask = (torch.arange(max_len).expand(batch_size, max_len).to(x.device) < seq_lengths.unsqueeze(1))
# Attention機構を適用
context_vector, attention_weights = self.attention(lstm_output, mask)
# ドロップアウト
context_vector = self.dropout(context_vector)
# 線形層を通して最終出力を得る
y = self.linear(context_vector)
return y.squeeze(1), attention_weights # 注意重みも返す(可視化などに使用可能)
このコードでは以下の変更を行いました:
Attention クラスを追加:LSTMの全時間ステップの出力に重み付けを行い、文脈ベクトルを生成します
AdvancedSequenceTaggingNet の変更点:
この実装により、モデルはシーケンス内の重要な部分に注目できるようになり、特に長いシーケンスや関連情報が分散している場合に効果を発揮します。