代码拉取完成,页面将自动刷新
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 2 15:05:26 2024
@author: QiJing
"""
import os
from transformers import BertTokenizer
import torch
from bert_get_data import BertClassifier
bert_name = './bert-base-chinese'
tokenizer = BertTokenizer.from_pretrained(bert_name)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
save_path = './bert_checkpoint'
model = BertClassifier()
model.load_state_dict(torch.load(os.path.join(save_path, 'best.pt')))
model = model.to(device)
model.eval()
real_labels = []
with open('./THUCNews/data/class.txt', 'r') as f:
for row in f.readlines():
real_labels.append(row.strip())
while True:
text = input('请输入新闻标题:')
bert_input = tokenizer(text, padding='max_length',
max_length = 35,
truncation=True,
return_tensors="pt")
input_ids = bert_input['input_ids'].to(device)
masks = bert_input['attention_mask'].unsqueeze(1).to(device)
output = model(input_ids, masks)
pred = output.argmax(dim=1)
print(real_labels[pred])
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。