1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
|
# 在代码开头添加
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer
import numpy as np
from typing import List, Dict, Optional
# ==================== 6.2 数据加载与预处理 ====================
class TextDataset(Dataset):
"""自定义文本数据集类"""
def __init__(self, texts: List[str], labels: List[int], tokenizer, max_length: int = 128):
"""
初始化数据集
参数:
texts: 文本列表
labels: 标签列表
tokenizer: 分词器
max_length: 最大序列长度
"""
self.texts = texts
self.labels = labels
self.tokenizer = tokenizer
self.max_length = max_length
def __len__(self) -> int:
"""返回数据集大小"""
return len(self.texts)
def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
"""获取单个样本"""
text = str(self.texts[idx])
label = self.labels[idx]
# 对文本进行编码
encoding = self.tokenizer(
text,
truncation=True,
padding='max_length',
max_length=self.max_length,
return_tensors='pt'
)
# 移除batch维度
item = {
'input_ids': encoding['input_ids'].flatten(),
'attention_mask': encoding['attention_mask'].flatten(),
'labels': torch.tensor(label, dtype=torch.long)
}
return item
# ==================== 模型训练与评估类 ====================
class TextClassifierTrainer:
"""文本分类训练器"""
def __init__(self,
model_name: str = "bert-base-uncased",
num_labels: int = 2,
device: Optional[str] = None):
"""
初始化训练器
参数:
model_name: 预训练模型名称
num_labels: 标签数量
device: 设备 (cpu/cuda)
"""
self.device = device if device else ('cuda' if torch.cuda.is_available() else 'cpu')
print(f"使用设备: {self.device}")
# 加载分词器和模型
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
self.model = AutoModelForSequenceClassification.from_pretrained(
model_name,
num_labels=num_labels
).to(self.device)
self.num_labels = num_labels
def create_dataloader(self,
texts: List[str],
labels: List[int],
batch_size: int = 32,
shuffle: bool = True,
max_length: int = 128) -> DataLoader:
"""
创建数据加载器
参数:
texts: 文本列表
labels: 标签列表
batch_size: 批次大小
shuffle: 是否打乱数据
max_length: 最大序列长度
"""
dataset = TextDataset(texts, labels, self.tokenizer, max_length)
dataloader = DataLoader(
dataset,
batch_size=batch_size,
shuffle=shuffle,
pin_memory=True if self.device == 'cuda' else False
)
return dataloader
def train(self,
train_loader: DataLoader,
val_loader: Optional[DataLoader] = None,
epochs: int = 3,
learning_rate: float = 5e-5,
save_path: str = "model.pt"):
"""
训练模型
参数:
train_loader: 训练数据加载器
val_loader: 验证数据加载器
epochs: 训练轮数
learning_rate: 学习率
save_path: 模型保存路径
"""
# 设置优化器
optimizer = optim.AdamW(self.model.parameters(), lr=learning_rate)
# 训练循环
for epoch in range(epochs):
print(f"\n{'='*50}")
print(f"Epoch {epoch + 1}/{epochs}")
print(f"{'='*50}")
# 训练模式
self.model.train()
total_loss = 0
correct = 0
total = 0
for batch_idx, batch in enumerate(train_loader):
# 将数据移动到设备
batch = {k: v.to(self.device) for k, v in batch.items()}
# 前向传播
outputs = self.model(**batch)
loss = outputs.loss
# 反向传播
loss.backward()
optimizer.step()
optimizer.zero_grad()
# 计算统计信息
total_loss += loss.item()
predictions = torch.argmax(outputs.logits, dim=-1)
correct += (predictions == batch['labels']).sum().item()
total += batch['labels'].size(0)
# 每100个batch打印一次进度
if (batch_idx + 1) % 100 == 0:
print(f" Batch {batch_idx + 1}/{len(train_loader)}, "
f"Loss: {loss.item():.4f}, "
f"Accuracy: {correct/total:.4f}")
# 计算epoch平均损失和准确率
avg_loss = total_loss / len(train_loader)
train_acc = correct / total
print(f"训练结果 - Loss: {avg_loss:.4f}, Accuracy: {train_acc:.4f}")
# 验证(如果提供了验证集)
if val_loader:
val_loss, val_acc = self.evaluate(val_loader)
print(f"验证结果 - Loss: {val_loss:.4f}, Accuracy: {val_acc:.4f}")
# 保存模型
self.save_model(save_path)
print(f"\n模型已保存到: {save_path}")
def evaluate(self, dataloader: DataLoader) -> tuple:
"""
评估模型
参数:
dataloader: 评估数据加载器
返回:
(平均损失, 准确率)
"""
self.model.eval()
total_loss = 0
correct = 0
total = 0
with torch.no_grad():
for batch in dataloader:
batch = {k: v.to(self.device) for k, v in batch.items()}
outputs = self.model(**batch)
total_loss += outputs.loss.item()
predictions = torch.argmax(outputs.logits, dim=-1)
correct += (predictions == batch['labels']).sum().item()
total += batch['labels'].size(0)
avg_loss = total_loss / len(dataloader)
accuracy = correct / total if total > 0 else 0
return avg_loss, accuracy
def predict(self, text: str) -> Dict:
"""
预测单个文本
参数:
text: 输入文本
返回:
预测结果字典
"""
self.model.eval()
# 编码文本
inputs = self.tokenizer(
text,
truncation=True,
padding='max_length',
max_length=128,
return_tensors='pt'
)
# 移动到设备
inputs = {k: v.to(self.device) for k, v in inputs.items()}
# 预测
with torch.no_grad():
outputs = self.model(**inputs)
probabilities = torch.softmax(outputs.logits, dim=-1)
prediction = torch.argmax(outputs.logits, dim=1).item()
return {
'text': text,
'prediction': prediction,
'probabilities': probabilities.cpu().numpy()[0].tolist(),
'confidence': probabilities.max().item()
}
def save_model(self, path: str):
"""保存模型"""
torch.save({
'model_state_dict': self.model.state_dict(),
'tokenizer_config': self.tokenizer.init_kwargs,
'model_config': self.model.config.to_dict(),
'num_labels': self.num_labels
}, path)
def load_model(self, path: str):
"""加载模型"""
checkpoint = torch.load(path, map_location=self.device)
self.model.load_state_dict(checkpoint['model_state_dict'])
self.num_labels = checkpoint['num_labels']
# ==================== 使用示例 ====================
def main():
"""主函数:演示完整流程"""
print("="*60)
print("文本分类完整流程演示")
print("="*60)
# 1. 准备示例数据
print("\n1. 准备数据...")
train_texts = [
"This product is amazing! I really love it.",
"Terrible experience, would not recommend.",
"The quality is good but delivery was late.",
"Excellent service and fast shipping.",
"Poor customer support, very disappointed.",
"Good value for money.",
"Not as described, very misleading.",
"Perfect! Exactly what I wanted."
]
train_labels = [1, 0, 1, 1, 0, 1, 0, 1] # 1: 正面, 0: 负面
test_texts = [
"I'm very satisfied with this purchase.",
"Waste of money, completely useless."
]
test_labels = [1, 0]
# 2. 初始化训练器
print("\n2. 初始化训练器...")
trainer = TextClassifierTrainer(
model_name="bert-base-uncased",
num_labels=2,
device='cpu' # 使用cpu,如需GPU请改为'cuda'
)
# 3. 创建数据加载器
print("\n3. 创建数据加载器...")
train_loader = trainer.create_dataloader(
train_texts, train_labels,
batch_size=2, shuffle=True, max_length=64
)
test_loader = trainer.create_dataloader(
test_texts, test_labels,
batch_size=2, shuffle=False, max_length=64
)
# 4. 训练模型
print("\n4. 开始训练模型...")
trainer.train(
train_loader=train_loader,
val_loader=test_loader,
epochs=3,
learning_rate=5e-5,
save_path="text_classifier_model.pt"
)
# 5. 加载模型并进行推理
print("\n5. 加载模型并进行推理...")
trainer.load_model("text_classifier_model.pt")
# 6. 测试推理
print("\n6. 测试推理...")
test_samples = [
"This is the best product I've ever bought!",
"I'm very disappointed with the quality.",
"It's okay, nothing special.",
"The service was absolutely fantastic!"
]
for text in test_samples:
result = trainer.predict(text)
sentiment = "正面" if result['prediction'] == 1 else "负面"
print(f"\n文本: {text}")
print(f"情感: {sentiment}")
print(f"置信度: {result['confidence']:.2%}")
print(f"概率分布: [负面: {result['probabilities'][0]:.4f}, 正面: {result['probabilities'][1]:.4f}]")
print("\n" + "="*60)
print("流程完成!")
print("="*60)
# ==================== 模型加载与推理的独立函数 ====================
def load_and_predict(model_path: str, text: str, device: str = None):
"""
加载模型并进行预测的独立函数
参数:
model_path: 模型路径
text: 输入文本
device: 设备类型
返回:
预测结果
"""
if device is None:
device = 'cuda' if torch.cuda.is_available() else 'cpu'
# 加载检查点
checkpoint = torch.load(model_path, map_location=device)
# 重新创建模型
model = AutoModelForSequenceClassification.from_pretrained(
"bert-base-uncased",
num_labels=checkpoint['num_labels']
).to(device)
# 加载权重
model.load_state_dict(checkpoint['model_state_dict'])
model.eval()
# 重新创建分词器
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
# 编码文本
inputs = tokenizer(
text,
truncation=True,
padding='max_length',
max_length=128,
return_tensors='pt'
).to(device)
# 预测
with torch.no_grad():
outputs = model(**inputs)
probabilities = torch.softmax(outputs.logits, dim=-1)
prediction = torch.argmax(outputs.logits, dim=1).item()
return {
'prediction': prediction,
'probabilities': probabilities.cpu().numpy()[0],
'confidence': probabilities.max().item()
}
if __name__ == "__main__":
# 运行完整演示
main()
# 示例:使用独立的加载和预测函数
print("\n\n独立函数调用示例:")
result = load_and_predict("text_classifier_model.pt", "This product is excellent!")
print(f"预测结果: {result}")
|