Yu,Zixuan commited on
Commit ·
0ee5b66
1
Parent(s): c6707e9
Create predict_bert.py
Browse files- predict_bert.py +81 -0
predict_bert.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import BertTokenizer, BertForSequenceClassification
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
def preprocess_text(text):
|
| 6 |
+
text = re.sub(r'[^\w\s]', '', text)
|
| 7 |
+
return text
|
| 8 |
+
|
| 9 |
+
def load_model():
|
| 10 |
+
# 加载预训练模型和分词器
|
| 11 |
+
model_name = 'bert-base-chinese'
|
| 12 |
+
tokenizer = BertTokenizer.from_pretrained(model_name)
|
| 13 |
+
model = BertForSequenceClassification.from_pretrained(model_name, num_labels=2)
|
| 14 |
+
|
| 15 |
+
# 加载训练好的模型参数
|
| 16 |
+
model.load_state_dict(torch.load('best_bert_model.pt'))
|
| 17 |
+
model.eval()
|
| 18 |
+
|
| 19 |
+
return model, tokenizer
|
| 20 |
+
|
| 21 |
+
def predict_text(text, model, tokenizer, device='cpu'):
|
| 22 |
+
# 预处理文本
|
| 23 |
+
processed_text = preprocess_text(text)
|
| 24 |
+
|
| 25 |
+
# 编码文本
|
| 26 |
+
encoding = tokenizer.encode_plus(
|
| 27 |
+
processed_text,
|
| 28 |
+
add_special_tokens=True,
|
| 29 |
+
max_length=128,
|
| 30 |
+
return_token_type_ids=False,
|
| 31 |
+
padding='max_length',
|
| 32 |
+
truncation=True,
|
| 33 |
+
return_attention_mask=True,
|
| 34 |
+
return_tensors='pt'
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
# 移动到设备
|
| 38 |
+
input_ids = encoding['input_ids'].to(device)
|
| 39 |
+
attention_mask = encoding['attention_mask'].to(device)
|
| 40 |
+
|
| 41 |
+
# 预测
|
| 42 |
+
with torch.no_grad():
|
| 43 |
+
outputs = model(
|
| 44 |
+
input_ids=input_ids,
|
| 45 |
+
attention_mask=attention_mask
|
| 46 |
+
)
|
| 47 |
+
_, preds = torch.max(outputs.logits, dim=1)
|
| 48 |
+
probs = torch.softmax(outputs.logits, dim=1)
|
| 49 |
+
|
| 50 |
+
return preds.item(), probs[0].cpu().numpy()
|
| 51 |
+
|
| 52 |
+
def main():
|
| 53 |
+
# 设置设备
|
| 54 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 55 |
+
print(f"使用设备: {device}")
|
| 56 |
+
|
| 57 |
+
# 加载模型
|
| 58 |
+
print("正在加载模型...")
|
| 59 |
+
model, tokenizer = load_model()
|
| 60 |
+
model = model.to(device)
|
| 61 |
+
print("模型加载完成!")
|
| 62 |
+
|
| 63 |
+
while True:
|
| 64 |
+
# 获取用户输入
|
| 65 |
+
text = input("\n请输入要预测的文本(输入'q'退出): ")
|
| 66 |
+
|
| 67 |
+
if text.lower() == 'q':
|
| 68 |
+
break
|
| 69 |
+
|
| 70 |
+
# 预测
|
| 71 |
+
pred, probs = predict_text(text, model, tokenizer, device)
|
| 72 |
+
|
| 73 |
+
# 输出结果
|
| 74 |
+
print("\n预测结果:")
|
| 75 |
+
print(f"文本: {text}")
|
| 76 |
+
print(f"预测标签: {pred}")
|
| 77 |
+
print(f"预测概率: 标签0的概率: {probs[0]:.4f}, 标签1的概率: {probs[1]:.4f}")
|
| 78 |
+
print("-" * 50)
|
| 79 |
+
|
| 80 |
+
if __name__ == "__main__":
|
| 81 |
+
main()
|