🚀 基金中文情感分析模型
本项目构建了一个基金方面的中文情感分析模型,利用约10w+的数据进行训练,在验证集上取得了较好的效果。该模型可用于判断基金相关文本的情感倾向,如积极、消极或中性。
🚀 快速开始
环境准备
确保你已经安装了torch
和transformers
库。可以使用以下命令进行安装:
pip install torch transformers
运行测试代码
将以下代码保存为一个Python文件(例如test.py
),并在命令行中运行:
python test.py [要分析的文本]
测试代码示例
import sys
import re
import torch
from transformers import BertTokenizer, BertForSequenceClassification
from torch.nn.functional import softmax
device = 'cuda' if torch.cuda.is_available() else 'cpu'
model = BertForSequenceClassification.from_pretrained('sanshizhang/Chinese-Sentiment-Analysis-Fund-Direction')
tokenizer = BertTokenizer.from_pretrained('sanshizhang/Chinese-Sentiment-Analysis-Fund-Direction')
model = model.to(device)
model.eval()
def predict_sentiment(text):
encoding = tokenizer.encode_plus(
text,
max_length=512,
add_special_tokens=True,
return_token_type_ids=False,
padding='max_length',
return_attention_mask=True,
return_tensors='pt',
truncation=True
)
input_ids = encoding['input_ids'].to(device)
attention_mask = encoding['attention_mask'].to(device)
with torch.no_grad():
outputs = model(input_ids=input_ids, attention_mask=attention_mask)
probs = softmax(outputs.logits, dim=1)
return probs, torch.argmax(probs, dim=1).cpu().numpy()[0]
arguments = sys.argv[1:]
text = ' '.join(arguments)
text = re.sub(r"[^\u4e00-\u9fff\d.a-zA-Z%+\-。!?,、;:()【】《》“”‘’]", '', text)
probabilities, prediction = predict_sentiment(text)
sentiment_labels = {0: 'negative', 1: 'positive', 2: 'neutral'}
predicted_sentiment = sentiment_labels[prediction]
print(f"Predicted sentiment: {predicted_sentiment},Probability:{probabilities[0][prediction].item()}")
✨ 主要特性
- 数据丰富:使用约10w+的数据进行训练,保证模型有足够的学习样本。
- 效果良好:在验证集上的准确度达到了0.9382193411826961。
- 功能明确:可准确判断基金相关中文文本的情感倾向。
🔧 技术细节
本模型基于BertForSequenceClassification
,使用BertTokenizer
进行文本编码。通过softmax
函数将模型输出的logits
转换为概率,从而进行情感分类。
📄 许可证
本项目采用Apache-2.0许可证。
验证集指标
验证集准确度
验证集准确度为0.9382193411826961。
验证集分类报告
类别 |
精确率 |
召回率 |
F1值 |
样本数 |
negative |
0.93 |
0.95 |
0.94 |
3785 |
positive |
0.95 |
0.96 |
0.95 |
6919 |
neutral |
0.93 |
0.89 |
0.91 |
4414 |
accuracy |
- |
- |
0.94 |
15118 |
macro avg |
0.94 |
0.93 |
0.93 |
15118 |
weighted avg |
0.94 |
0.94 |
0.94 |
15118 |
返回值解释
- 0: 'negative'(消极)
- 1: 'positive'(积极)
- 2: 'neutral'(中性)
注意事项
负面方面的文本经过专人处理,而中性文本的判断可能不够准确。