我还想要可视化训练结果
- User
我还想要可视化训练结果
Assistant
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 matplotlib.pyplot as plt
import seaborn as sns
from typing import List, Tuple
# ---------------------- 增强的训练函数(记录损失) ----------------------
def train_with_history(model, train_loader, optimizer, criterion, device, epochs=10):
model.train()
loss_history = [] # 记录每个epoch的平均损失
for epoch in range(epochs):
total_loss = 0.0
batch_losses = [] # 记录每个batch的损失
for batch_idx, (src, tgt) in enumerate(train_loader):
src = src.to(device)
tgt = tgt.to(device)
tgt_input = tgt[:, :-1]
tgt_output = tgt[:, 1:]
tgt_mask = model.generate_square_subsequent_mask(tgt_input.size(1)).to(device)
src_mask = None
src_pad_mask = (src == 0)
tgt_pad_mask = (tgt_input == 0)
optimizer.zero_grad()
output = model(
src=src,
tgt=tgt_input,
src_mask=src_mask,
tgt_mask=tgt_mask,
src_key_padding_mask=src_pad_mask,
tgt_key_padding_mask=tgt_pad_mask
)
loss = criterion(
output.reshape(-1, output.size(-1)),
tgt_output.reshape(-1)
)
loss.backward()
optimizer.step()
batch_losses.append(loss.item())
total_loss += loss.item() * src.size(0)
avg_loss = total_loss / len(train_loader.dataset)
loss_history.append(avg_loss)
print(f"Epoch {epoch+1:2d}, Average Loss: {avg_loss:.4f}")
return loss_history
# ---------------------- 可视化损失曲线 ----------------------
def plot_loss_curve(loss_history: List[float], save_path: str = 'loss_curve.png'):
plt.figure(figsize=(10, 6))
plt.plot(loss_history, 'b-', linewidth=2, label='Training Loss')
plt.xlabel('Epoch', fontsize=12)
plt.ylabel('Loss', fontsize=12)
plt.title('Training Loss over Epochs', fontsize=14)
plt.grid(True, alpha=0.3)
plt.legend()
plt.tight_layout()
plt.savefig(save_path, dpi=300)
plt.show()
# ---------------------- 推理函数(贪婪解码) ----------------------
def greedy_decode(
model: nn.Module,
src: torch.Tensor,
max_len: int,
start_symbol: int = 1, # 开始符号
end_symbol: int = 2, # 结束符号
device: str = 'cpu'
) -> torch.Tensor:
model.eval()
# 编码源序列
src = src.unsqueeze(0).to(device) # 添加batch维度
src_mask = None
src_pad_mask = (src == 0)
with torch.no_grad():
# 获取编码器输出
src_emb = model.pos_encoding(model.src_embedding(src) * math.sqrt(model.src_embedding.embedding_dim))
memory = model.encoder(src_emb, src_mask, src_pad_mask)
# 初始化解码器输入
ys = torch.ones(1, 1).fill_(start_symbol).type(torch.long).to(device)
for i in range(max_len - 1):
# 生成掩码
tgt_mask = model.generate_square_subsequent_mask(ys.size(1)).to(device)
# 解码器前向传播
tgt_emb = model.pos_encoding(model.tgt_embedding(ys) * math.sqrt(model.tgt_embedding.embedding_dim))
decoder_output = model.decoder(tgt_emb, memory, tgt_mask, None, src_pad_mask)
output = model.fc_out(decoder_output)
# 贪婪选择:选择概率最大的token
prob = output[:, -1, :] # 取最后一个位置的输出
_, next_word = torch.max(prob, dim=1)
next_word = next_word.item()
# 添加预测的token
ys = torch.cat([ys, torch.ones(1, 1).type_as(src.data).fill_(next_word)], dim=1)
# 如果预测到结束符号,停止
if next_word == end_symbol:
break
return ys
# ---------------------- 可视化翻译示例 ----------------------
def visualize_translation_examples(
model: nn.Module,
test_data: List[Tuple[torch.Tensor, torch.Tensor]],
vocab_src: dict = None, # 源语言词汇表 {idx: word}
vocab_tgt: dict = None, # 目标语言词汇表 {idx: word}
num_examples: int = 3,
device: str = 'cpu'
):
model.eval()
for i in range(min(num_examples, len(test_data))):
src, tgt = test_data[i]
src = src[src != 0] # 移除填充
tgt = tgt[tgt != 0] # 移除填充
# 贪婪解码
translation = greedy_decode(model, src, max_len=50, device=device)
translation = translation.squeeze(0)[1:] # 移除batch维度和开始符号
# 转换为文本(如果有词汇表)
if vocab_src:
src_text = ' '.join([vocab_src.get(idx.item(), f'<{idx.item()}>') for idx in src])
else:
src_text = ' '.join([str(idx.item()) for idx in src])
if vocab_tgt:
tgt_text = ' '.join([vocab_tgt.get(idx.item(), f'<{idx.item()}>') for idx in tgt])
trans_text = ' '.join([vocab_tgt.get(idx.item(), f'<{idx.item()}>') for idx in translation])
else:
tgt_text = ' '.join([str(idx.item()) for idx in tgt])
trans_text = ' '.join([str(idx.item()) for idx in translation])
print(f"\nExample {i+1}:")
print(f"Source: {src_text}")
print(f"Target: {tgt_text}")
print(f"Translation: {trans_text}")
运行以上代码后,你将得到以下可视化结果:
training_loss.png):展示损失随epoch的下降趋势encoder_attention.png):展示编码器自注意力权重分布decoder_cross_attention.png):展示解码器如何关注源序列training_statistics.png):包含损失下降率和对数损失曲线这些可视化能帮助你:
如需更详细的评估,可以加入BLEU分数计算、困惑度(perplexity)等指标。
# ---------------------- 提取注意力权重的Transformer(用于可视化) ----------------------
class TransformerWithAttentionWeights(Transformer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.encoder_attention_weights = []
self.decoder_self_attention_weights = []
self.decoder_cross_attention_weights = []
def forward(self, src, tgt, src_mask=None, tgt_mask=None,
src_key_padding_mask=None, tgt_key_padding_mask=None):
# 清空之前的注意力权重
self.encoder_attention_weights = []
self.decoder_self_attention_weights = []
self.decoder_cross_attention_weights = []
# 嵌入 + 位置编码
src_emb = self.pos_encoding(self.src_embedding(src) * math.sqrt(self.src_embedding.embedding_dim))
tgt_emb = self.pos_encoding(self.tgt_embedding(tgt) * math.sqrt(self.tgt_embedding.embedding_dim))
# 编码器前向传播(记录注意力权重)
memory = src_emb
for encoder_layer in self.encoder.layers:
# 手动调用注意力层以获取权重
attn_output, attn_weights = encoder_layer.self_attn(
memory, memory, memory,
attn_mask=src_mask,
key_padding_mask=src_key_padding_mask,
need_weights=True,
average_attn_weights=True
)
self.encoder_attention_weights.append(attn_weights.detach().cpu())
# 完成剩余的编码器层计算
memory = memory + encoder_layer.dropout1(attn_output)
memory = encoder_layer.norm1(memory)
ff_output = encoder_layer.linear2(encoder_layer.dropout(F.relu(encoder_layer.linear1(memory))))
memory = memory + encoder_layer.dropout2(ff_output)
memory = encoder_layer.norm2(memory)
memory = self.encoder.norm(memory)
# 解码器前向传播(记录注意力权重)
output = tgt_emb
for decoder_layer in self.decoder.layers:
# 自注意力
self_attn_output, self_attn_weights = decoder_layer.self_attn(
output, output, output,
attn_mask=tgt_mask,
key_padding_mask=tgt_key_padding_mask,
need_weights=True,
average_attn_weights=True
)
self.decoder_self_attention_weights.append(self_attn_weights.detach().cpu())
output = output + decoder_layer.dropout1(self_attn_output)
output = decoder_layer.norm1(output)
# 交叉注意力
cross_attn_output, cross_attn_weights = decoder_layer.multihead_attn(
output, memory, memory,
key_padding_mask=src_key_padding_mask,
need_weights=True,
average_attn_weights=True
)
self.decoder_cross_attention_weights.append(cross_attn_weights.detach().cpu())
output = output + decoder_layer.dropout2(cross_attn_output)
output = decoder_layer.norm2(output)
# 前馈网络
ff_output = decoder_layer.linear2(decoder_layer.dropout(F.relu(decoder_layer.linear1(output))))
output = output + decoder_layer.dropout3(ff_output)
output = decoder_layer.norm3(output)
output = self.decoder.norm(output)
output = self.fc_out(output)
return output
# ---------------------- 可视化注意力权重 ----------------------
def plot_attention_weights(
attention_weights: torch.Tensor,
input_labels: List[str] = None,
output_labels: List[str] = None,
title: str = "Attention Weights",
save_path: str = None
):
# attention_weights: (batch_size, num_heads, seq_len_q, seq_len_k)
# 取第一个样本的平均注意力权重
weights = attention_weights[0].mean(dim=0).numpy() # (seq_len_q, seq_len_k)
plt.figure(figsize=(10, 8))
sns.heatmap(
weights,
cmap='Blues',
cbar=True,
xticklabels=input_labels if input_labels else range(weights.shape[1]),
yticklabels=output_labels if output_labels else range(weights.shape[0]),
fmt='.2f',
square=True
)
plt.title(title, fontsize=14)
plt.xlabel('Keys (Input)', fontsize=12)
plt.ylabel('Queries (Output)', fontsize=12)
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=300)
plt.show()
# ---------------------- 带可视化的主函数 ----------------------
def main_with_visualization():
# 配置参数
src_vocab_size = 100 # 减小词汇表以便可视化
tgt_vocab_size = 100
d_model = 128
num_encoder_layers = 2
num_decoder_layers = 2
nhead = 4
dim_feedforward = 512
dropout = 0.1
max_seq_length = 20
batch_size = 16
num_samples = 300
epochs = 10
pad_idx = 0
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 创建数据集
dataset = MockTranslationDataset(
src_vocab_size=src_vocab_size,
tgt_vocab_size=tgt_vocab_size,
max_seq_len=max_seq_length,
num_samples=num_samples
)
train_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
# 保留一些测试样本
test_data = [(dataset[i][0], dataset[i][1]) for i in range(5)]
# 创建带注意力权重的模型
model = TransformerWithAttentionWeights(
src_vocab_size=src_vocab_size,
tgt_vocab_size=tgt_vocab_size,
d_model=d_model,
num_encoder_layers=num_encoder_layers,
num_decoder_layers=num_decoder_layers,
nhead=nhead,
dim_feedforward=dim_feedforward,
dropout=dropout,
max_seq_length=max_seq_length,
pad_idx=pad_idx
).to(device)
# 优化器和损失函数
optimizer = optim.Adam(model.parameters(), lr=1e-3, betas=(0.9, 0.98), eps=1e-9)
criterion = nn.CrossEntropyLoss(ignore_index=pad_idx)
# 1. 训练模型
print("=== Training Model ===")
loss_history = train_with_history(model, train_loader, optimizer, criterion, device, epochs)
# 2. 绘制损失曲线
print("\n=== Plotting Loss Curve ===")
plot_loss_curve(loss_history, 'training_loss.png')
# 3. 可视化注意力权重
print("\n=== Visualizing Attention Weights ===")
model.eval()
with torch.no_grad():
# 获取一个样本
src, tgt = test_data[0]
src = src.unsqueeze(0).to(device)
tgt = tgt.unsqueeze(0).to(device)
tgt_input = tgt[:, :-1]
# 生成掩码
tgt_mask = model.generate_square_subsequent_mask(tgt_input.size(1)).to(device)
src_pad_mask = (src == 0)
tgt_pad_mask = (tgt_input == 0)
# 前向传播(会记录注意力权重)
_ = model(src, tgt_input, None, tgt_mask, src_pad_mask, tgt_pad_mask)
# 可视化编码器自注意力(最后一层)
if model.encoder_attention_weights:
plot_attention_weights(
model.encoder_attention_weights[-1],
title="Encoder Self-Attention (Last Layer)",
save_path="encoder_attention.png"
)
# 可视化解码器交叉注意力(最后一层)
if model.decoder_cross_attention_weights:
plot_attention_weights(
model.decoder_cross_attention_weights[-1],
title="Decoder Cross-Attention (Last Layer)",
save_path="decoder_cross_attention.png"
)
# 4. 翻译示例
print("\n=== Translation Examples ===")
visualize_translation_examples(model, test_data, num_examples=3, device=device)
# 5. 训练过程统计图表
print("\n=== Training Statistics ===")
fig, axes = plt.subplots(1, 2, figsize=(15, 5))
# 损失下降率
axes[0].bar(range(1, len(loss_history)),
[loss_history[i-1] - loss_history[i] for i in range(1, len(loss_history))],
color='green', alpha=0.7)
axes[0].set_xlabel('Epoch')
axes[0].set_ylabel('Loss Reduction')
axes[0].set_title('Loss Reduction per Epoch')
axes[0].grid(True, alpha=0.3)
# 损失对数图
axes[1].semilogy(loss_history, 'r-', linewidth=2)
axes[1].set_xlabel('Epoch')
axes[1].set_ylabel('Loss (log scale)')
axes[1].set_title('Training Loss (Log Scale)')
axes[1].grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('training_statistics.png', dpi=300)
plt.show()
# ---------------------- 添加BLEU分数计算(可选) ----------------------
def calculate_bleu_score(reference: List[int], hypothesis: List[int], max_n: int = 4) -> float:
"""简化的BLEU分数计算(用于单个句子)"""
from collections import Counter
bleu_scores = []
for n in range(1, min(max_n + 1, min(len(reference), len(hypothesis)) + 1)):
ref_ngrams = Counter([tuple(reference[i:i+n]) for i in range(len(reference)-n+1)])
hyp_ngrams = Counter([tuple(hypothesis[i:i+n]) for i in range(len(hypothesis)-n+1)])
matches = sum((ref_ngrams & hyp_ngrams).values())
total = sum(hyp_ngrams.values())
if total > 0:
precision = matches / total
bleu_scores.append(precision)
else:
bleu_scores.append(0.0)
if not bleu_scores:
return 0.0
# 几何平均
bleu = 1.0
for score in bleu_scores:
bleu *= score ** (1.0 / len(bleu_scores))
# 长度惩罚
bp = min(1.0, math.exp(1 - len(reference) / max(len(hypothesis), 1)))
return bp * bleu
if __name__ == "__main__":
main_with_visualization()