bread-good111 commited on
Commit
d96281d
·
verified ·
1 Parent(s): 7e692f7

Delete inference_example.py

Browse files
Files changed (1) hide show
  1. inference_example.py +0 -91
inference_example.py DELETED
@@ -1,91 +0,0 @@
1
- """
2
- 情感检测推理示例
3
- 使用detection_hug模型进行情感分类
4
- """
5
- import torch
6
- from transformers import BertTokenizer
7
- from detection_model import EmotionDetectionModel
8
-
9
- def load_model(model_path="model.pt", device="cpu"):
10
- """加载模型"""
11
- print(f"加载模型: {model_path}")
12
-
13
- # 加载分词器
14
- tokenizer = BertTokenizer.from_pretrained(".")
15
-
16
- # 创建模型
17
- model = EmotionDetectionModel(
18
- model_name="bert-base-chinese",
19
- num_emotions=6,
20
- dropout=0.1
21
- )
22
-
23
- # 加载权重
24
- checkpoint = torch.load(model_path, map_location=device)
25
- if isinstance(checkpoint, dict) and 'model_state_dict' in checkpoint:
26
- model.load_state_dict(checkpoint['model_state_dict'])
27
- else:
28
- model.load_state_dict(checkpoint)
29
-
30
- model = model.to(device)
31
- model.eval()
32
-
33
- print("✅ 模型加载成功")
34
- return model, tokenizer
35
-
36
- def predict(text, model, tokenizer, device="cpu"):
37
- """预测单个文本的情感"""
38
- # 情感标签
39
- EMOTIONS = ["sadness", "joy", "love", "anger", "fear", "surprise"]
40
-
41
- # 编码
42
- encoding = tokenizer(
43
- text,
44
- padding='max_length',
45
- truncation=True,
46
- max_length=512,
47
- return_tensors='pt'
48
- )
49
-
50
- input_ids = encoding['input_ids'].to(device)
51
- attention_mask = encoding['attention_mask'].to(device)
52
-
53
- # 推理
54
- with torch.no_grad():
55
- outputs = model(input_ids=input_ids, attention_mask=attention_mask)
56
- logits = outputs['logits']
57
- probabilities = torch.softmax(logits, dim=-1)
58
- predicted_id = torch.argmax(probabilities, dim=-1).item()
59
- confidence = probabilities[0, predicted_id].item()
60
-
61
- return {
62
- 'emotion': EMOTIONS[predicted_id],
63
- 'confidence': confidence,
64
- 'all_probabilities': {
65
- EMOTIONS[i]: float(probabilities[0, i])
66
- for i in range(len(EMOTIONS))
67
- }
68
- }
69
-
70
- if __name__ == "__main__":
71
- # 示例
72
- device = "cuda" if torch.cuda.is_available() else "cpu"
73
- model, tokenizer = load_model(device=device)
74
-
75
- # 测试文本
76
- test_texts = [
77
- "我今天很开心!",
78
- "这让我感到非常难过。",
79
- "我爱你。"
80
- ]
81
-
82
- print("\n" + "="*60)
83
- print("情感检测结果")
84
- print("="*60)
85
-
86
- for text in test_texts:
87
- result = predict(text, model, tokenizer, device)
88
- print(f"\n文本: {text}")
89
- print(f"情感: {result['emotion']}")
90
- print(f"置信度: {result['confidence']:.4f}")
91
-