黄页88网站关键词怎么做,安徽省通信建设管理局网站,北京seo运营推广,怎样做58网站Bert实现文本分类微调Demo import random
from collections import namedtuple
有四种文本需要做分类#xff0c;请使用bert处理这个分类问题
# 使用namedtuple定义一个类别(Category)#xff0c;包含两个字段#xff1a;名称(name)和样例(samples)
Category namedtuple(Ca… Bert实现文本分类微调Demo import random
from collections import namedtuple
有四种文本需要做分类请使用bert处理这个分类问题
# 使用namedtuple定义一个类别(Category)包含两个字段名称(name)和样例(samples)
Category namedtuple(Category, [name, samples])# 定义四个不同的类别及其对应的样例文本
categories [Category(Weather Forecast, [今天北京晴转多云气温20-25度。, 明天上海有小雨记得带伞。]), # 天气预报类别的样例Category(Company Financial Report, [本季度公司净利润增长20%。, 年度财务报告显示成本控制良好。]), # 公司财报类别的样例Category(Company Audit Materials, [审计发现内部控制存在漏洞。, 审计确认财务报表无重大错报。]), # 公司审计材料类别的样例Category(Product Marketing Ad, [新口味可乐清爽上市, 买一送一仅限今日。]) # 产品营销广告类别的样例
]def generate_data(num_samples_per_category50): 生成模拟数据集输入:- num_samples_per_category: 每个类别生成的样本数量默认为50输出:- data: 包含文本样本及其对应类别的列表每项为一个元组(text, label)data [] # 初始化存储数据的列表for category in categories: # 遍历所有类别for _ in range(num_samples_per_category): # 对每个类别生成指定数量的样本sample random.choice(category.samples) # 从该类别的样例中随机选择一条文本data.append((sample, category.name)) # 将文本及其类别添加到data列表中return data# 调用generate_data函数生成模拟数据集
train_data generate_data(100) # 为每个类别生成100个训练样本
test_data generate_data(6) # 生成少量6个测试样本用于演示
train_data
[(明天上海有小雨记得带伞。, Weather Forecast),(明天上海有小雨记得带伞。, Weather Forecast),(今天北京晴转多云气温20-25度。, Weather Forecast),(今天北京晴转多云气温20-25度。, Weather Forecast),(今天北京晴转多云气温20-25度。, Weather Forecast),(明天上海有小雨记得带伞。, Weather Forecast),(明天上海有小雨记得带伞。, Weather Forecast),(明天上海有小雨记得带伞。, Weather Forecast),(今天北京晴转多云气温20-25度。, Weather Forecast),]
from transformers import BertTokenizer, BertForSequenceClassification, AdamW
from torch.utils.data import DataLoader, TensorDataset
import torch
import torch.nn.functional as F# 步骤1: 定义类别到标签的映射
label_map {category.name: index for index, category in enumerate(categories)}
num_labels len(categories) # 类别总数# 步骤2: 初始化BERT分词器和模型
tokenizer BertTokenizer.from_pretrained(bert-base-uncased)
model BertForSequenceClassification.from_pretrained(bert-base-uncased, num_labelsnum_labels)# 步骤3: 准备数据集
def encode_texts(texts, labels):# 对文本进行编码得到BERT模型需要的输入格式encodings tokenizer(texts, truncationTrue, paddingTrue, return_tensorspt)# 将标签名称转换为对应的索引label_ids torch.tensor([label_map[label] for label in labels])return encodings, label_idsdef prepare_data(data):texts, labels zip(*data) # 解压数据encodings, label_ids encode_texts(texts, labels) # 编码数据dataset TensorDataset(encodings[input_ids], encodings[attention_mask], label_ids) # 创建数据集return DataLoader(dataset, batch_size8, shuffleTrue) # 创建数据加载器# 步骤4: 准备训练和测试数据
train_loader prepare_data(train_data)
test_loader prepare_data(test_data)# 步骤5: 定义训练和评估函数
device torch.device(cuda if torch.cuda.is_available() else cpu)
model.to(device)def train_epoch(model, data_loader, optimizer):model.train()total_loss 0for batch in data_loader:optimizer.zero_grad()input_ids, attention_mask, labels batchinput_ids, attention_mask, labels input_ids.to(device), attention_mask.to(device), labels.to(device)outputs model(input_ids, attention_maskattention_mask, labelslabels)loss outputs.losstotal_loss loss.item()loss.backward()optimizer.step()return total_loss / len(data_loader)def evaluate(model, data_loader):model.eval()total_acc 0total_count 0with torch.no_grad():for batch in data_loader:input_ids, attention_mask, labels batchinput_ids, attention_mask, labels input_ids.to(device), attention_mask.to(device), labels.to(device)outputs model(input_ids, attention_maskattention_mask)predictions torch.argmax(outputs.logits, dim1)total_acc (predictions labels).sum().item()total_count labels.size(0)return total_acc / total_count# 步骤6: 训练模型
optimizer AdamW(model.parameters(), lr2e-5)for epoch in range(3): # 训练3个epochtrain_loss train_epoch(model, train_loader, optimizer)acc evaluate(model, test_loader)print(fEpoch {epoch1}, Train Loss: {train_loss}, Test Accuracy: {acc*100:.2f}%)# 步骤7: 使用微调后的模型进行预测
def predict(text):encodings tokenizer(text, truncationTrue, paddingTrue, return_tensorspt)input_ids encodings[input_ids].to(device)attention_mask encodings[attention_mask].to(device)with torch.no_grad():outputs model(input_ids, attention_maskattention_mask)predicted_class_id torch.argmax(outputs.logits).item()return categories[predicted_class_id].name# 预测一个新文本
new_text [明天的天气怎么样] # 注意这里是一个列表
predicted_category predict(new_text)
print(fThe predicted category for the new text is: {predicted_category}) 文章转载自: http://www.morning.nwllb.cn.gov.cn.nwllb.cn http://www.morning.dkmzr.cn.gov.cn.dkmzr.cn http://www.morning.sjgsh.cn.gov.cn.sjgsh.cn http://www.morning.wqpb.cn.gov.cn.wqpb.cn http://www.morning.hhskr.cn.gov.cn.hhskr.cn http://www.morning.qqhmg.cn.gov.cn.qqhmg.cn http://www.morning.rytps.cn.gov.cn.rytps.cn http://www.morning.c7500.cn.gov.cn.c7500.cn http://www.morning.mnygn.cn.gov.cn.mnygn.cn http://www.morning.jzmqk.cn.gov.cn.jzmqk.cn http://www.morning.kflzy.cn.gov.cn.kflzy.cn http://www.morning.jkpnm.cn.gov.cn.jkpnm.cn http://www.morning.qfplp.cn.gov.cn.qfplp.cn http://www.morning.rbxsk.cn.gov.cn.rbxsk.cn http://www.morning.wkrkb.cn.gov.cn.wkrkb.cn http://www.morning.ghryk.cn.gov.cn.ghryk.cn http://www.morning.ljmbd.cn.gov.cn.ljmbd.cn http://www.morning.ttcmdsg.cn.gov.cn.ttcmdsg.cn http://www.morning.yknsr.cn.gov.cn.yknsr.cn http://www.morning.bwmm.cn.gov.cn.bwmm.cn http://www.morning.wptrm.cn.gov.cn.wptrm.cn http://www.morning.nhrkl.cn.gov.cn.nhrkl.cn http://www.morning.yhpq.cn.gov.cn.yhpq.cn http://www.morning.tclqf.cn.gov.cn.tclqf.cn http://www.morning.lxfyn.cn.gov.cn.lxfyn.cn http://www.morning.ftnhr.cn.gov.cn.ftnhr.cn http://www.morning.bqfpm.cn.gov.cn.bqfpm.cn http://www.morning.hxbjt.cn.gov.cn.hxbjt.cn http://www.morning.sfwfk.cn.gov.cn.sfwfk.cn http://www.morning.jfzbk.cn.gov.cn.jfzbk.cn http://www.morning.nggry.cn.gov.cn.nggry.cn http://www.morning.wyfpc.cn.gov.cn.wyfpc.cn http://www.morning.xwlhc.cn.gov.cn.xwlhc.cn http://www.morning.bfmq.cn.gov.cn.bfmq.cn http://www.morning.tfzjl.cn.gov.cn.tfzjl.cn http://www.morning.thlr.cn.gov.cn.thlr.cn http://www.morning.xiaobaixinyong.cn.gov.cn.xiaobaixinyong.cn http://www.morning.nllst.cn.gov.cn.nllst.cn http://www.morning.nngq.cn.gov.cn.nngq.cn http://www.morning.rrdch.cn.gov.cn.rrdch.cn http://www.morning.ykqbs.cn.gov.cn.ykqbs.cn http://www.morning.gccdr.cn.gov.cn.gccdr.cn http://www.morning.nfnxp.cn.gov.cn.nfnxp.cn http://www.morning.whnps.cn.gov.cn.whnps.cn http://www.morning.jwxmn.cn.gov.cn.jwxmn.cn http://www.morning.mgzjz.cn.gov.cn.mgzjz.cn http://www.morning.rgzc.cn.gov.cn.rgzc.cn http://www.morning.lqjlg.cn.gov.cn.lqjlg.cn http://www.morning.rkrl.cn.gov.cn.rkrl.cn http://www.morning.qxxj.cn.gov.cn.qxxj.cn http://www.morning.tnfyj.cn.gov.cn.tnfyj.cn http://www.morning.tztgq.cn.gov.cn.tztgq.cn http://www.morning.qlckc.cn.gov.cn.qlckc.cn http://www.morning.jcwt.cn.gov.cn.jcwt.cn http://www.morning.trlhc.cn.gov.cn.trlhc.cn http://www.morning.reababy.com.gov.cn.reababy.com http://www.morning.xmpbh.cn.gov.cn.xmpbh.cn http://www.morning.jlnlr.cn.gov.cn.jlnlr.cn http://www.morning.mrxqd.cn.gov.cn.mrxqd.cn http://www.morning.hfnbr.cn.gov.cn.hfnbr.cn http://www.morning.qtbnm.cn.gov.cn.qtbnm.cn http://www.morning.wfkbk.cn.gov.cn.wfkbk.cn http://www.morning.rqhdt.cn.gov.cn.rqhdt.cn http://www.morning.znqxt.cn.gov.cn.znqxt.cn http://www.morning.qbzfp.cn.gov.cn.qbzfp.cn http://www.morning.ynryz.cn.gov.cn.ynryz.cn http://www.morning.mnsmb.cn.gov.cn.mnsmb.cn http://www.morning.qsctt.cn.gov.cn.qsctt.cn http://www.morning.mnkz.cn.gov.cn.mnkz.cn http://www.morning.rhpgk.cn.gov.cn.rhpgk.cn http://www.morning.dkzrs.cn.gov.cn.dkzrs.cn http://www.morning.spwln.cn.gov.cn.spwln.cn http://www.morning.lqlc.cn.gov.cn.lqlc.cn http://www.morning.gglhj.cn.gov.cn.gglhj.cn http://www.morning.mhfbf.cn.gov.cn.mhfbf.cn http://www.morning.jwefry.cn.gov.cn.jwefry.cn http://www.morning.sbrpz.cn.gov.cn.sbrpz.cn http://www.morning.bkwd.cn.gov.cn.bkwd.cn http://www.morning.kdpal.cn.gov.cn.kdpal.cn http://www.morning.fkmqg.cn.gov.cn.fkmqg.cn