Python朴素贝叶斯情感分析代码示例 - 识别积极、消极和中性情绪
以下是一个基于朴素贝叶斯算法实现情感分析(积极、消极、中性)的 Python 代码示例:
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score
# 下载必要的数据集和模型
nltk.download('punkt')
nltk.download('stopwords')
nltk.download('wordnet')
# 加载数据集
data = [
('I love this product', 'positive'),
('This is the worst product ever', 'negative'),
('I am neutral about this product', 'neutral'),
# 更多的训练数据...
]
# 数据预处理
lemmatizer = WordNetLemmatizer()
stop_words = set(stopwords.words('english'))
def preprocess(text):
# 分词
tokens = word_tokenize(text.lower())
# 去除停用词和标点符号
tokens = [token for token in tokens if token.isalpha() and token not in stop_words]
# 词形还原
tokens = [lemmatizer.lemmatize(token) for token in tokens]
# 返回处理后的文本
return ' '.join(tokens)
# 提取特征
corpus = [preprocess(text) for text, _ in data]
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(corpus)
y = [label for _, label in data]
# 训练模型
model = MultinomialNB()
model.fit(X, y)
# 进行预测
test_data = [
'I hate this product',
'This product is awesome',
'I have no opinion about this product',
# 更多的测试数据...
]
X_test = vectorizer.transform([preprocess(text) for text in test_data])
y_pred = model.predict(X_test)
# 输出预测结果
for text, label in zip(test_data, y_pred):
print(f'{text} -> {label}')
# 计算准确率
y_true = ['negative', 'positive', 'neutral'] # 测试数据的真实标签
accuracy = accuracy_score(y_true, y_pred)
print(f'Accuracy: {accuracy:.2f}')
在上述代码中,我们首先加载了必要的数据集和模型,然后定义了一个 preprocess() 函数用于对输入的文本进行预处理,包括分词、去除停用词和标点符号、词形还原等操作。接着,我们使用 CountVectorizer 提取文本特征,并使用朴素贝叶斯算法训练了一个情感分析模型。最后,我们使用模型对一些测试数据进行预测,并计算了预测结果的准确率。
原文地址: https://www.cveoy.top/t/topic/oSNl 著作权归作者所有。请勿转载和采集!