核心内容摘要
一级A视频精彩内容推荐:点燃你的视界,解锁无限可能
大家好我是锋哥。
最近发布一条【AI大模型舆情分析】微博舆情分析可视化系统(pytorch2基于BERT大模型训练微调flaskpandasecharts高级实战。
分上下节。
实战简介前面的2026版【NLP舆情分析】基于python微博舆情分析可视化系统(flaskpandasecharts爬虫) 二次开发前面课程舆情分析用得是snowNLP我们现在改用基于BERT开源大模型微调来实现舆情分析提高舆情分析的准确率。
重点讲解基本BERT大模型实现舆情分析二分类问题。
视频教程和源码领取链接https://pan.baidu.com/s/1_NzaNr0Wln6kv1rdiQnUTg提取码0000微博舆情分析可视化系统 - 项目准备基于python微博舆情分析可视化系统(flaskpandasecharts) 项目源码本地运行下。
登录页面我们改下小标题加个LLM登录后进入系统主页面BERT大模型实现舆情分析功能大模型开发环境准备-PyTorch和transformers库首先新建model目录把Bert-base-chinese粘贴到model目录下。
我们大模型训练尽可能的基于GPU的CUDA要安装下。
然后我们要安装Pytorch2和transformers库pip install torch torchvision --index-url https://download.pytorch.org/whl/cu126pip install transformers -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com环境测试代码import torch from transformers import pipeline print(torch.cuda.is_available()) # 通过pipeline 加载模型 model pipeline(tasktext-classification, # 任务类型 二分类 modelBert-base-chinese, # 模型名称 device0 # 使用GPU ) # 调用模型预测 result model(小明是好学生) print(result)运行结果BERT大模型情感分析功能封装使用AutoModel自动模型方式新建llm目录里面再新建weibo.py文件代码实现import torch from transformers import AutoTokenizer, AutoModelForSequenceClassification # 使用设备GPU device torch.device(cuda if torch.cuda.is_available() else cpu) print(device) # 加载分词器 tokenizer AutoTokenizer.from_pretrained(../model/Bert-base-chinese) # 加载模型 model AutoModelForSequenceClassification.from_pretrained(../model/Bert-base-chinese) print(model) # 情感分析 def data_classfication(data): # 准备输入数据 input_ids tokenizer.encode( textdata, # 输入文本 return_tensorspt, # 返回PyTorch张量 truncationTrue, # 截断超过长度的输入文本 max_length20, # 最长长度 paddingmax_length # 填充短的输入文本 ).to(device) # 评估模型 model.eval() model.to(device) # 模型预测 output model(input_ids) print(output) # 获取预测结果 logits output.logits print(logits) predication torch.argmax(logits, dim-
print(predication) sentiment predication.item() # 把张量转成数字 print(sentiment) sentiment_label 正面 if sentiment 1 else 负面 return sentiment_label if __name__ __main__: result data_classfication(开心) print(预测结果, result)运行结果使用BERT大模型对微博热词进行情感分析找到视图层业务逻辑代码我们修改下# 改成使用大模型进行舆情分析 sentiments data_classfication(defaultHotWord)启动就直接报错了原因是加载模型用得是相对路径我们调用封装方法的时候相对路径又变了。
所以我们企业级开发一般不用相对路径只用绝对路径由于开发环境测试环境线上环境模型路径会变所以我们一般都会把路径放到配置文件里面去方便修改路径。
我们在项目根目录下新建config.py配置下模型路径# 定义模型路径 model_path D:\python_pro\weiboLLMProject2\model接下来weibo.py里把相对路径改成绝对路径使用config.py里的model_path属性改成# 加载分词器 tokenizer AutoTokenizer.from_pretrained(config.model_path /Bert-base-chinese) # 加载模型 model AutoModelForSequenceClassification.from_pretrained(config.model_path /Bert-base-chinese) print(model)运行测试系统可以了。
不过情感分析的准确率很有限等后面VIP课程我们使用增量微调训练后的模型准确率能上到90%以上。
使用BERT大模型对微博文章内容进行情感分析找到微博舆情分析后端视图业务逻辑代码改成# 改成使用大模型进行舆情分析 sentiments data_classfication(article[1])重启项目测试使用BERT大模型对微博舆情分析以及可视化操作找到数据可视化微博舆情分析后端视图层业务逻辑代码包括柱状图树形图饼状图。
代码都需要修改代码修改pb.route(sentimentAnalysis) def sentimentAnalysis(): 舆情数据分析 :return: xHotBarData [正面, 负面] yHotBarData [0, 0] # 只读取前100条 df pd.read_csv(./fenci/comment_fre.csv, nrows