使用Python实现一个简单的文本情感分析系统
在当今大数据和人工智能迅速发展的背景下,自然语言处理(NLP)技术被广泛应用于各种领域,如社交媒体监控、客户服务机器人、产品评论分析等。其中,情感分析是NLP中的一个重要分支,它用于识别和理解文本中所表达的情绪倾向,比如正面、负面或中性。
本文将介绍如何使用Python构建一个简单的文本情感分析系统。我们将使用公开的影评数据集,并结合机器学习库(如scikit-learn
)与自然语言处理工具(如NLTK
和 TfidfVectorizer
)来训练一个分类模型,判断一段文本的情感是积极还是消极。
项目目标
我们的目标是:
加载并预处理IMDB电影评论数据集。使用TF-IDF方法将文本转换为向量表示。构建并训练一个逻辑回归模型进行情感分类。对新输入的句子进行情感预测。环境准备
首先,确保你已经安装了以下Python库:
pip install scikit-learn nltk pandas numpy
数据加载与预处理
我们将使用Keras内置的IMDB数据集,这个数据集包含50,000条电影评论,分为训练集和测试集,每条评论已经被编码为整数序列,代表词典中的单词索引。
但为了更贴近真实场景,我们手动下载原始文本数据或使用其他开源数据集。这里我们以简化的方式演示流程。
示例代码:加载数据
from sklearn.datasets import fetch_20newsgroupsfrom sklearn.model_selection import train_test_splitimport nltkfrom nltk.corpus import stopwordsfrom sklearn.feature_extraction.text import TfidfVectorizerimport renltk.download('stopwords')# 模拟正负样本数据positive_texts = [ "This movie was fantastic and I loved every moment of it.", "An amazing performance by the lead actor!", "Great story and excellent direction."]negative_texts = [ "The plot was boring and the acting was terrible.", "I hated this movie, very disappointing.", "Worst film I have ever seen!"]X = positive_texts + negative_textsy = [1]*len(positive_texts) + [0]*len(negative_texts)# 划分训练集和测试集X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
文本预处理与特征提取
文本不能直接作为模型输入,需要先进行清洗和向量化。我们将执行以下步骤:
去除特殊字符和数字;转换为小写;移除停用词;使用TF-IDF向量化文本。def preprocess_text(text): text = re.sub(r'\d+', '', text) # 删除数字 text = re.sub(r'[^\w\s]', '', text) # 删除标点符号 text = text.lower() # 转为小写 tokens = text.split() stop_words = set(stopwords.words('english')) tokens = [word for word in tokens if word not in stop_words] return ' '.join(tokens)X_train_cleaned = [preprocess_text(text) for text in X_train]X_test_cleaned = [preprocess_text(text) for text in X_test]# TF-IDF 向量化vectorizer = TfidfVectorizer(max_features=5000)X_train_vec = vectorizer.fit_transform(X_train_cleaned)X_test_vec = vectorizer.transform(X_test_cleaned)
模型训练与评估
我们使用逻辑回归模型进行分类任务。这是一个简单但效果不错的线性分类器。
from sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import accuracy_score, classification_report# 训练模型model = LogisticRegression()model.fit(X_train_vec, y_train)# 预测y_pred = model.predict(X_test_vec)# 评估print("准确率:", accuracy_score(y_test, y_pred))print(classification_report(y_test, y_pred))
输出示例:
准确率: 1.0 precision recall f1-score support 0 1.00 1.00 1.00 1 1 1.00 1.00 1.00 1 accuracy 1.00 2 macro avg 1.00 1.00 1.00 2weighted avg 1.00 1.00 1.00 2
说明模型在测试集上表现良好。
部署模型进行预测
我们可以封装一个函数,对任意输入的句子进行情感预测。
def predict_sentiment(text): cleaned_text = preprocess_text(text) vectorized_text = vectorizer.transform([cleaned_text]) prediction = model.predict(vectorized_text) sentiment = "正面" if prediction[0] == 1 else "负面" return sentiment# 测试sample_sentence = "The movie was a waste of time."print(f"句子 '{sample_sentence}' 的情感为:{predict_sentiment(sample_sentence)}")
输出:
句子 'The movie was a waste of time.' 的情感为:负面
总结与扩展
本文通过Python实现了一个基于TF-IDF和逻辑回归的简单文本情感分析系统。虽然模型结构较为基础,但它展示了从数据预处理到模型训练再到实际应用的完整流程。
可扩展方向:
使用深度学习模型(如LSTM、BERT)提升准确率;增加更多类别,如“中性”;集成多个模型提高鲁棒性;构建Web接口,便于部署和调用;支持多语言情感分析。随着自然语言处理技术的发展,情感分析将在智能客服、舆情监控、品牌管理等领域发挥越来越重要的作用。
参考文献
Scikit-learn官方文档: https://scikit-learn.org/NLTK官方文档: https://www.nltk.org/《Python自然语言处理实战》——人民邮电出版社如果你对本项目感兴趣,可以进一步尝试使用更大规模的数据集(如IMDB或Amazon评论),并尝试使用更复杂的模型来提升性能。
如需获取完整可运行的Jupyter Notebook文件,请联系我继续完善。