上传预训练模型文件及代码
Browse files- pinyin2hanzi_transformer.pth +3 -0
- run.py +434 -0
pinyin2hanzi_transformer.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a7d0c8e588e83f1d9b8dc9c961cca4410a5b20f6f6d912f854553ca2a0234b7b
|
| 3 |
+
size 250775353
|
run.py
ADDED
|
@@ -0,0 +1,434 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
- Copyright (c) 2025 DuYu (No.202103180009, [email protected]), Faculty of Computer Science and Technology, Qilu University of Technology (Shandong Academy of Sciences).
|
| 3 |
+
- 基于Transformer的汉语拼音序列转汉字序列模型 训练与测试代码
|
| 4 |
+
- 文件名:run.py
|
| 5 |
+
"""
|
| 6 |
+
import re
|
| 7 |
+
import warnings
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import matplotlib.pyplot as plt
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
import torch.optim as optim
|
| 14 |
+
import torch.nn.functional as F
|
| 15 |
+
from torch.utils.data import Dataset, DataLoader
|
| 16 |
+
from tqdm import tqdm
|
| 17 |
+
from collections import Counter
|
| 18 |
+
|
| 19 |
+
warnings.filterwarnings("ignore") # 全局禁用警告信息,开发时可去除
|
| 20 |
+
|
| 21 |
+
# 设置随机种子保证可重复性
|
| 22 |
+
torch.manual_seed(525200)
|
| 23 |
+
np.random.seed(40004004)
|
| 24 |
+
|
| 25 |
+
# 检查是否有可用的GPU
|
| 26 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 27 |
+
print(f"Using device: {device}")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# 1. 数据读取与预处理
|
| 31 |
+
class PinyinHanziDataset(Dataset):
|
| 32 |
+
def __init__(self, csv_file, max_length=15):
|
| 33 |
+
self.data = pd.read_csv(csv_file, header=None, names=['hanzi', 'pinyin'])
|
| 34 |
+
self.max_length = max_length
|
| 35 |
+
|
| 36 |
+
# 构建词汇表
|
| 37 |
+
self._build_vocab()
|
| 38 |
+
|
| 39 |
+
def _tokenize_hanzi(self, s):
|
| 40 |
+
"""将文本分割为汉字、英文单词和标点符号的混合token"""
|
| 41 |
+
pattern = re.compile(
|
| 42 |
+
r'([\u4e00-\u9fff\u3000-\u303f\uff00-\uffef]|[a-zA-Z.,!?;:\'"]+|\d+|\s)'
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
tokens = []
|
| 46 |
+
for token in pattern.finditer(s):
|
| 47 |
+
if token.group().strip(): # 忽略纯空格
|
| 48 |
+
tokens.append(token.group())
|
| 49 |
+
|
| 50 |
+
return tokens
|
| 51 |
+
|
| 52 |
+
def _build_vocab(self):
|
| 53 |
+
# 处理汉字词汇表
|
| 54 |
+
hanzi_counter = Counter()
|
| 55 |
+
pinyin_counter = Counter()
|
| 56 |
+
|
| 57 |
+
for _, row in self.data.iterrows():
|
| 58 |
+
# 使用新的tokenize方法处理汉字
|
| 59 |
+
hanzi_tokens = self._tokenize_hanzi(row['hanzi'])
|
| 60 |
+
hanzi_counter.update(hanzi_tokens)
|
| 61 |
+
|
| 62 |
+
# 拼音处理:按空格分割
|
| 63 |
+
pinyin_tokens = row['pinyin'].split()
|
| 64 |
+
pinyin_counter.update(pinyin_tokens)
|
| 65 |
+
|
| 66 |
+
# 添加特殊token
|
| 67 |
+
self.hanzi_vocab = ['<pad>', '<unk>', '<sos>', '<eos>'] + [char for char, _ in hanzi_counter.most_common()]
|
| 68 |
+
self.pinyin_vocab = ['<pad>', '<unk>', '<sos>', '<eos>'] + [pinyin for pinyin, _ in
|
| 69 |
+
pinyin_counter.most_common()]
|
| 70 |
+
|
| 71 |
+
# 创建token到id的映射
|
| 72 |
+
self.hanzi2idx = {char: idx for idx, char in enumerate(self.hanzi_vocab)}
|
| 73 |
+
self.idx2hanzi = {idx: char for idx, char in enumerate(self.hanzi_vocab)}
|
| 74 |
+
self.pinyin2idx = {pinyin: idx for idx, pinyin in enumerate(self.pinyin_vocab)}
|
| 75 |
+
self.idx2pinyin = {idx: pinyin for idx, pinyin in enumerate(self.pinyin_vocab)}
|
| 76 |
+
|
| 77 |
+
def __len__(self):
|
| 78 |
+
return len(self.data)
|
| 79 |
+
|
| 80 |
+
def __getitem__(self, idx):
|
| 81 |
+
hanzi_seq = self.data.iloc[idx]['hanzi']
|
| 82 |
+
pinyin_seq = self.data.iloc[idx]['pinyin']
|
| 83 |
+
|
| 84 |
+
# 将汉字序列转换为token id序列
|
| 85 |
+
hanzi_tokens = ['<sos>'] + self._tokenize_hanzi(hanzi_seq) + ['<eos>']
|
| 86 |
+
hanzi_ids = [self.hanzi2idx.get(token, self.hanzi2idx['<unk>']) for token in hanzi_tokens]
|
| 87 |
+
|
| 88 |
+
# 将拼音序列转换为token id序列
|
| 89 |
+
pinyin_tokens = ['<sos>'] + pinyin_seq.split() + ['<eos>']
|
| 90 |
+
pinyin_ids = [self.pinyin2idx.get(token, self.pinyin2idx['<unk>']) for token in pinyin_tokens]
|
| 91 |
+
|
| 92 |
+
# 截断或填充序列
|
| 93 |
+
hanzi_ids = hanzi_ids[:self.max_length]
|
| 94 |
+
pinyin_ids = pinyin_ids[:self.max_length]
|
| 95 |
+
|
| 96 |
+
hanzi_padding = [self.hanzi2idx['<pad>']] * (self.max_length - len(hanzi_ids))
|
| 97 |
+
pinyin_padding = [self.pinyin2idx['<pad>']] * (self.max_length - len(pinyin_ids))
|
| 98 |
+
|
| 99 |
+
hanzi_ids += hanzi_padding
|
| 100 |
+
pinyin_ids += pinyin_padding
|
| 101 |
+
|
| 102 |
+
return {
|
| 103 |
+
'pinyin': torch.tensor(pinyin_ids, dtype=torch.long),
|
| 104 |
+
'hanzi': torch.tensor(hanzi_ids, dtype=torch.long),
|
| 105 |
+
'hanzi_input': torch.tensor(hanzi_ids[:-1], dtype=torch.long),
|
| 106 |
+
'hanzi_target': torch.tensor(hanzi_ids[1:], dtype=torch.long)
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
# 2. Transformer模型定义
|
| 111 |
+
class TransformerModel(nn.Module):
|
| 112 |
+
def __init__(self, pinyin_vocab_size, hanzi_vocab_size, d_model=256, nhead=8, num_encoder_layers=6,
|
| 113 |
+
num_decoder_layers=6, dim_feedforward=1024, dropout=0.075):
|
| 114 |
+
super(TransformerModel, self).__init__()
|
| 115 |
+
|
| 116 |
+
self.d_model = d_model
|
| 117 |
+
|
| 118 |
+
# 拼音嵌入层
|
| 119 |
+
self.pinyin_embedding = nn.Embedding(pinyin_vocab_size, d_model)
|
| 120 |
+
# 汉字嵌入层
|
| 121 |
+
self.hanzi_embedding = nn.Embedding(hanzi_vocab_size, d_model)
|
| 122 |
+
|
| 123 |
+
# 位置编码
|
| 124 |
+
self.positional_encoding = PositionalEncoding(d_model, dropout)
|
| 125 |
+
|
| 126 |
+
# Transformer模型
|
| 127 |
+
self.transformer = nn.Transformer(
|
| 128 |
+
d_model=d_model,
|
| 129 |
+
nhead=nhead,
|
| 130 |
+
num_encoder_layers=num_encoder_layers,
|
| 131 |
+
num_decoder_layers=num_decoder_layers,
|
| 132 |
+
dim_feedforward=dim_feedforward,
|
| 133 |
+
dropout=dropout
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
# 输出层
|
| 137 |
+
self.fc_out = nn.Linear(d_model, hanzi_vocab_size)
|
| 138 |
+
|
| 139 |
+
def forward(self, pinyin, hanzi_input):
|
| 140 |
+
# 嵌入层
|
| 141 |
+
pinyin_embedded = self.pinyin_embedding(pinyin) * np.sqrt(self.d_model)
|
| 142 |
+
hanzi_embedded = self.hanzi_embedding(hanzi_input) * np.sqrt(self.d_model)
|
| 143 |
+
|
| 144 |
+
# 位置编码
|
| 145 |
+
pinyin_embedded = self.positional_encoding(pinyin_embedded)
|
| 146 |
+
hanzi_embedded = self.positional_encoding(hanzi_embedded)
|
| 147 |
+
|
| 148 |
+
# 调整维度顺序:(seq_len, batch_size, d_model)
|
| 149 |
+
pinyin_embedded = pinyin_embedded.permute(1, 0, 2)
|
| 150 |
+
hanzi_embedded = hanzi_embedded.permute(1, 0, 2)
|
| 151 |
+
|
| 152 |
+
# 创建mask
|
| 153 |
+
src_mask = self._generate_square_subsequent_mask(pinyin_embedded.size(0)).to(device)
|
| 154 |
+
tgt_mask = self._generate_square_subsequent_mask(hanzi_embedded.size(0)).to(device)
|
| 155 |
+
|
| 156 |
+
# Transformer前向传播
|
| 157 |
+
output = self.transformer(
|
| 158 |
+
src=pinyin_embedded,
|
| 159 |
+
tgt=hanzi_embedded,
|
| 160 |
+
src_key_padding_mask=self._create_padding_mask(pinyin),
|
| 161 |
+
tgt_key_padding_mask=self._create_padding_mask(hanzi_input),
|
| 162 |
+
memory_key_padding_mask=self._create_padding_mask(pinyin),
|
| 163 |
+
src_mask=src_mask,
|
| 164 |
+
tgt_mask=tgt_mask
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
# 输出层,输出前将维度调整回(batch_size, seq_len, d_model)
|
| 168 |
+
output = output.permute(1, 0, 2)
|
| 169 |
+
output = self.fc_out(output)
|
| 170 |
+
|
| 171 |
+
return output
|
| 172 |
+
|
| 173 |
+
def _generate_square_subsequent_mask(self, sz):
|
| 174 |
+
return torch.triu(torch.full((sz, sz), float('-inf')), diagonal=1)
|
| 175 |
+
|
| 176 |
+
def _create_padding_mask(self, seq):
|
| 177 |
+
return seq == 0 # 假设<pad>的id是0
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
# 3. 位置编码定义
|
| 181 |
+
class PositionalEncoding(nn.Module):
|
| 182 |
+
def __init__(self, d_model, dropout=0.1, max_len=512):
|
| 183 |
+
super(PositionalEncoding, self).__init__()
|
| 184 |
+
self.dropout = nn.Dropout(p=dropout)
|
| 185 |
+
|
| 186 |
+
position = torch.arange(max_len).unsqueeze(1)
|
| 187 |
+
div_term = torch.exp(torch.arange(0, d_model, 2) * (-np.log(10000.0) / d_model))
|
| 188 |
+
pe = torch.zeros(max_len, 1, d_model)
|
| 189 |
+
pe[:, 0, 0::2] = torch.sin(position * div_term)
|
| 190 |
+
pe[:, 0, 1::2] = torch.cos(position * div_term)
|
| 191 |
+
self.register_buffer('pe', pe)
|
| 192 |
+
|
| 193 |
+
def forward(self, x):
|
| 194 |
+
x = x + self.pe[:x.size(0)]
|
| 195 |
+
return self.dropout(x)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
# 4. 建模(包装器定义)
|
| 199 |
+
class PinyinHanziTransformer:
|
| 200 |
+
def __init__(self, model=None, dataset=None, config=None):
|
| 201 |
+
self.model = model
|
| 202 |
+
self.dataset = dataset
|
| 203 |
+
self.config = config or {}
|
| 204 |
+
|
| 205 |
+
def save(self, filepath):
|
| 206 |
+
"""保存整个模型、词汇表和配置到单个文件"""
|
| 207 |
+
save_data = {
|
| 208 |
+
'model_state_dict': self.model.state_dict(),
|
| 209 |
+
'hanzi_vocab': self.dataset.hanzi_vocab,
|
| 210 |
+
'pinyin_vocab': self.dataset.pinyin_vocab,
|
| 211 |
+
'hanzi2idx': self.dataset.hanzi2idx,
|
| 212 |
+
'idx2hanzi': self.dataset.idx2hanzi,
|
| 213 |
+
'pinyin2idx': self.dataset.pinyin2idx,
|
| 214 |
+
'idx2pinyin': self.dataset.idx2pinyin,
|
| 215 |
+
'max_length': self.dataset.max_length,
|
| 216 |
+
'config': self.config
|
| 217 |
+
}
|
| 218 |
+
torch.save(save_data, filepath)
|
| 219 |
+
|
| 220 |
+
@classmethod
|
| 221 |
+
def load(cls, filepath, device='cpu'):
|
| 222 |
+
"""从文件加载整个模型"""
|
| 223 |
+
save_data = torch.load(filepath, map_location=device)
|
| 224 |
+
|
| 225 |
+
# 创建虚拟数据集对象以保存词汇表信息
|
| 226 |
+
class DummyDataset:
|
| 227 |
+
pass
|
| 228 |
+
|
| 229 |
+
dataset = DummyDataset()
|
| 230 |
+
dataset.hanzi_vocab = save_data['hanzi_vocab']
|
| 231 |
+
dataset.pinyin_vocab = save_data['pinyin_vocab']
|
| 232 |
+
dataset.hanzi2idx = save_data['hanzi2idx']
|
| 233 |
+
dataset.idx2hanzi = save_data['idx2hanzi']
|
| 234 |
+
dataset.pinyin2idx = save_data['pinyin2idx']
|
| 235 |
+
dataset.idx2pinyin = save_data['idx2pinyin']
|
| 236 |
+
dataset.max_length = save_data['max_length']
|
| 237 |
+
|
| 238 |
+
# 初始化模型
|
| 239 |
+
config = save_data['config']
|
| 240 |
+
model = TransformerModel(
|
| 241 |
+
pinyin_vocab_size=len(dataset.pinyin_vocab),
|
| 242 |
+
hanzi_vocab_size=len(dataset.hanzi_vocab),
|
| 243 |
+
**config
|
| 244 |
+
).to(device)
|
| 245 |
+
model.load_state_dict(save_data['model_state_dict'])
|
| 246 |
+
|
| 247 |
+
return cls(model=model, dataset=dataset, config=config)
|
| 248 |
+
|
| 249 |
+
@staticmethod
|
| 250 |
+
def top_k_sampling(logits, k=5, temperature=1.0):
|
| 251 |
+
logits = logits / temperature
|
| 252 |
+
probs = F.softmax(logits, dim=-1) # shape: (1, vocab_size)
|
| 253 |
+
|
| 254 |
+
topk_probs, topk_indices = torch.topk(probs, k, dim=-1) # shape: (1, k)
|
| 255 |
+
|
| 256 |
+
# 从 top-k 中随机采样一个 index(在 top k 里的位置)
|
| 257 |
+
sampled_index = torch.multinomial(topk_probs, num_samples=1) # shape: (1, 1)
|
| 258 |
+
|
| 259 |
+
# 找到对应的真正 vocab 索引
|
| 260 |
+
next_token = torch.gather(topk_indices, dim=1, index=sampled_index) # shape: (1, 1)
|
| 261 |
+
|
| 262 |
+
# Instead of directly using .item(), ensure we're handling the tensor correctly
|
| 263 |
+
return next_token.squeeze().item() # .squeeze() to get rid of the extra dimension and then .item()
|
| 264 |
+
|
| 265 |
+
def predict(self, pinyin_seq, max_length=None, k=3, temperature=1.0):
|
| 266 |
+
"""预测函数(使用top-k采样)"""
|
| 267 |
+
self.model.eval()
|
| 268 |
+
max_length = max_length or self.dataset.max_length
|
| 269 |
+
|
| 270 |
+
# 拼音转ID
|
| 271 |
+
pinyin_tokens = ['<sos>'] + pinyin_seq.split() + ['<eos>']
|
| 272 |
+
pinyin_ids = [self.dataset.pinyin2idx.get(token, self.dataset.pinyin2idx['<unk>']) for token in pinyin_tokens]
|
| 273 |
+
pinyin_ids = pinyin_ids[:max_length]
|
| 274 |
+
pinyin_ids += [self.dataset.pinyin2idx['<pad>']] * (max_length - len(pinyin_ids))
|
| 275 |
+
pinyin_tensor = torch.tensor(pinyin_ids, dtype=torch.long).unsqueeze(0).to(self.model.device)
|
| 276 |
+
|
| 277 |
+
# 初始化汉字序列
|
| 278 |
+
hanzi_ids = [self.dataset.hanzi2idx['<sos>']]
|
| 279 |
+
|
| 280 |
+
for i in range(max_length - 1):
|
| 281 |
+
hanzi_tensor = torch.tensor(hanzi_ids, dtype=torch.long).unsqueeze(0).to(self.model.device)
|
| 282 |
+
|
| 283 |
+
with torch.no_grad():
|
| 284 |
+
output = self.model(pinyin_tensor, hanzi_tensor) # (1, seq_len, vocab_size)
|
| 285 |
+
logits = output[:, -1, :] # 取最后一个位置的logits,(1, vocab_size)
|
| 286 |
+
|
| 287 |
+
# 使用top-k采样
|
| 288 |
+
next_token = PinyinHanziTransformer.top_k_sampling(logits, k=k, temperature=temperature)
|
| 289 |
+
hanzi_ids.append(next_token)
|
| 290 |
+
|
| 291 |
+
if next_token == self.dataset.hanzi2idx['<eos>']:
|
| 292 |
+
break
|
| 293 |
+
|
| 294 |
+
# 转换为汉字序列
|
| 295 |
+
hanzi_seq = [self.dataset.idx2hanzi[idx] for idx in hanzi_ids[1:-1]] # 去掉<sos>和可能的<eos>
|
| 296 |
+
return ''.join(hanzi_seq)
|
| 297 |
+
|
| 298 |
+
# 在TransformerModel类中添加device属性
|
| 299 |
+
@property
|
| 300 |
+
def device(self):
|
| 301 |
+
return next(self.parameters()).device
|
| 302 |
+
|
| 303 |
+
TransformerModel.device = device
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
# 5. 训练函数定义
|
| 307 |
+
def train_model(model, dataloader, optimizer, criterion, epoch):
|
| 308 |
+
model.train()
|
| 309 |
+
total_loss = 0
|
| 310 |
+
progress_bar = tqdm(dataloader, desc=f"Epoch {epoch}")
|
| 311 |
+
|
| 312 |
+
for batch in progress_bar:
|
| 313 |
+
pinyin = batch['pinyin'].to(device)
|
| 314 |
+
hanzi_input = batch['hanzi_input'].to(device)
|
| 315 |
+
hanzi_target = batch['hanzi_target'].to(device)
|
| 316 |
+
|
| 317 |
+
# 前向传播
|
| 318 |
+
output = model(pinyin, hanzi_input)
|
| 319 |
+
|
| 320 |
+
# 计算损失
|
| 321 |
+
loss = criterion(output.reshape(-1, output.size(-1)), hanzi_target.reshape(-1))
|
| 322 |
+
|
| 323 |
+
# 反向传播
|
| 324 |
+
optimizer.zero_grad()
|
| 325 |
+
loss.backward()
|
| 326 |
+
optimizer.step()
|
| 327 |
+
|
| 328 |
+
total_loss += loss.item()
|
| 329 |
+
progress_bar.set_postfix(loss=f"{loss.item():.3f}")
|
| 330 |
+
|
| 331 |
+
return total_loss / len(dataloader)
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
# 4. 评估函数定义
|
| 335 |
+
def evaluate_model(model, dataloader, criterion):
|
| 336 |
+
model.eval()
|
| 337 |
+
total_loss = 0
|
| 338 |
+
|
| 339 |
+
with torch.no_grad():
|
| 340 |
+
for batch in tqdm(dataloader, desc="Evaluating"):
|
| 341 |
+
pinyin = batch['pinyin'].to(device)
|
| 342 |
+
hanzi_input = batch['hanzi_input'].to(device)
|
| 343 |
+
hanzi_target = batch['hanzi_target'].to(device)
|
| 344 |
+
|
| 345 |
+
output = model(pinyin, hanzi_input)
|
| 346 |
+
loss = criterion(output.reshape(-1, output.size(-1)), hanzi_target.reshape(-1))
|
| 347 |
+
total_loss += loss.item()
|
| 348 |
+
|
| 349 |
+
return total_loss / len(dataloader)
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
# 6. 模型训练主函数
|
| 353 |
+
def train_main():
|
| 354 |
+
# 参数设置 训练前请调整这些参数
|
| 355 |
+
batch_size = 256 # 批大小
|
| 356 |
+
num_epochs = 33 # 迭代轮数
|
| 357 |
+
learning_rate = 0.0001 # 学习率
|
| 358 |
+
max_length = 14 # 截断长度
|
| 359 |
+
train_test_ratio = 0.95 # 数据集中训练集与测试集数据量比例
|
| 360 |
+
dataset_filepath = 'pinyin2hanzi.csv' # 数据集CSV文件路径
|
| 361 |
+
model_config = { # 模型配置参数
|
| 362 |
+
'd_model': 512, # 词嵌入维度
|
| 363 |
+
'nhead': 16, # 多头注意力层注意力头数
|
| 364 |
+
'num_encoder_layers': 8, # Transformer编码器块数
|
| 365 |
+
'num_decoder_layers': 6, # Transformer解码器块数
|
| 366 |
+
'dim_feedforward': 1024, # Transformer前馈层维度
|
| 367 |
+
'dropout': 0.07 # dropout比例
|
| 368 |
+
}
|
| 369 |
+
|
| 370 |
+
# 加载数据集
|
| 371 |
+
dataset = PinyinHanziDataset(dataset_filepath, max_length=max_length)
|
| 372 |
+
|
| 373 |
+
# 分割训练集和测试集
|
| 374 |
+
train_size = int(train_test_ratio * len(dataset))
|
| 375 |
+
test_size = len(dataset) - train_size
|
| 376 |
+
train_dataset, test_dataset = torch.utils.data.random_split(dataset, [train_size, test_size])
|
| 377 |
+
|
| 378 |
+
# 创建DataLoader
|
| 379 |
+
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
|
| 380 |
+
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
|
| 381 |
+
|
| 382 |
+
# 初始化模型包装器
|
| 383 |
+
transformer = PinyinHanziTransformer(
|
| 384 |
+
model=TransformerModel(
|
| 385 |
+
pinyin_vocab_size=len(dataset.pinyin_vocab),
|
| 386 |
+
hanzi_vocab_size=len(dataset.hanzi_vocab),
|
| 387 |
+
**model_config
|
| 388 |
+
).to(device),
|
| 389 |
+
dataset=dataset,
|
| 390 |
+
config=model_config
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
# 损失函数和优化器
|
| 394 |
+
criterion = nn.CrossEntropyLoss(ignore_index=dataset.hanzi2idx['<pad>'])
|
| 395 |
+
optimizer = optim.Adam(transformer.model.parameters(), lr=learning_rate)
|
| 396 |
+
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=45, gamma=0.41)
|
| 397 |
+
|
| 398 |
+
# 训练循环
|
| 399 |
+
train_losses = []
|
| 400 |
+
test_losses = []
|
| 401 |
+
|
| 402 |
+
for epoch in range(1, num_epochs + 1):
|
| 403 |
+
train_loss = train_model(transformer.model, train_loader, optimizer, criterion, epoch)
|
| 404 |
+
test_loss = evaluate_model(transformer.model, test_loader, criterion)
|
| 405 |
+
|
| 406 |
+
train_losses.append(train_loss)
|
| 407 |
+
test_losses.append(test_loss)
|
| 408 |
+
|
| 409 |
+
scheduler.step()
|
| 410 |
+
print(f"Epoch {epoch}: Train Loss = {train_loss:.4f}, Test Loss = {test_loss:.4f}")
|
| 411 |
+
|
| 412 |
+
# 保存整个模型到当前目录(包括词汇表等信息)
|
| 413 |
+
# if epoch % 7 == 0 or epoch == num_epochs:
|
| 414 |
+
transformer.save(f"pinyin2hanzi_transformer_epoch{epoch}.pth")
|
| 415 |
+
|
| 416 |
+
# 绘制损失曲线
|
| 417 |
+
plt.plot(train_losses, label='Train Loss')
|
| 418 |
+
plt.plot(test_losses, label='Test Loss')
|
| 419 |
+
plt.xlabel('Epoch')
|
| 420 |
+
plt.ylabel('Loss')
|
| 421 |
+
plt.legend()
|
| 422 |
+
plt.savefig('loss_curve.png')
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
# 7. 模型推理主函数
|
| 426 |
+
def use_main():
|
| 427 |
+
transformer = PinyinHanziTransformer.load("pinyin2hanzi_transformer.pth", device=str(device))
|
| 428 |
+
result = transformer.predict("hong2 yan2 bo2 ming4") # 应当输出:红颜薄命
|
| 429 |
+
print("预测结果: ", result)
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
if __name__ == "__main__":
|
| 433 |
+
# train_main() # 解除注释、修改参数,运行代码以开始训练
|
| 434 |
+
use_main() # 解除注释以使用模型
|