朴素贝叶斯文本分类的python代码
时间: 2023-09-13 19:07:40 浏览: 120
以下是一个基本的朴素贝叶斯文本分类器的Python代码示例:
```python
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
# 读取训练数据
train_data = pd.read_csv('train_data.csv')
# 提取文本特征
vectorizer = CountVectorizer()
X_train = vectorizer.fit_transform(train_data.text)
y_train = train_data.label
# 训练朴素贝叶斯分类器
clf = MultinomialNB()
clf.fit(X_train, y_train)
# 读取测试数据
test_data = pd.read_csv('test_data.csv')
# 对测试数据进行预测
X_test = vectorizer.transform(test_data.text)
y_test = test_data.label
y_pred = clf.predict(X_test)
# 输出分类器的准确率
accuracy = clf.score(X_test, y_test)
print("Accuracy:", accuracy)
```
在这个示例中,我们使用了Pandas库来读取和处理文本数据。我们使用了CountVectorizer来提取文本特征,这会将文本转换为一组数字特征,以便我们可以将其输入分类器中。我们使用了sklearn库中的MultinomialNB类来训练朴素贝叶斯分类器,并使用它来预测测试数据。最后,我们输出了分类器的准确率。
阅读全文
相关推荐












