🚀 基金中文情感分析模型
本項目構建了一個基金方面的中文情感分析模型,利用約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'(中性)
注意事項
負面方面的文本經過專人處理,而中性文本的判斷可能不夠準確。