本系列文章配套代码获取有以下两种途径:
-
通过百度网盘获取:
链接:https://pan.baidu.com/s/1i9F6oV1J5oZnIsOASDs0gQ?pwd=mnsj
提取码:mnsj
-
前往GitHub获取:
https://github.com/returu/Python_mini_program
脚本需求:
实现步骤:
-
1、加载数据,用于创建训练数据和测试数据:
CSV文件的格式要求:
I love this sandwich.,pos
This is an amazing place!,pos
I do not like this restaurant,neg
JSON文件的格式要求:
[
{"text": "I love this sandwich.", "label": "pos"},
{"text": "This is an amazing place!", "label": "pos"},
{"text": "I do not like this restaurant", "label": "neg"}
]
-
2、自定义特征提取器:
默认情况下,NaiveBayesClassifier使用一个简单的特征提取器,它指示训练集中哪些单词包含在文档中。可以通过编写自定义的特征提取器来覆盖默认的特征提取器。
特征提取器只是一个函数,其第一个参数为document(要从中提取特征的文本),如果需要,该函数可以包含第二个参数train_set(训练数据集)。该函数应返回一个包含document特征的字典。
然后,通过将其作为构造函数的第二个参数传递给分类器来使用该特征提取器。
-
3、创建分类器:
-
4、使用分类器对文本或者TextBlob进行分类:
-
对文本进行分类:调用cl.classify(text)方法来使用分类器,使用cl.prob_classify(text)方法获取标签的概率分布。 -
对TextBlob进行分类:将分类器传递给TextBlob的构造函数,并调用其classify()方法。这种方法的优点是,可以对TextBlob中的句子进行分类。
-
5、评估分类器;
-
使用accuracy(test_data)方法可以计算分类器在测试集上的准确率。 -
使用show_informative_features()方法显示分类器中最有信息量的特征,这些特征通常是那些对分类决策影响最大的单词或短语,通过调用该方法,可以了解哪些特征对分类器的决策过程最为重要
-
6、使用新数据更新分类器:
代码实现:
具体代码如下所示:
import csv
from textblob import TextBlob
from textblob.classifiers import NaiveBayesClassifier , DecisionTreeClassifier
# ----------------------
# 1. 加载数据:
# ----------------------
# 从CSV文件中读取数据
def read_data_from_csv(file_path):
data = []
with open(file_path, 'r', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
next(reader) # 跳过第一行标题
for row in reader:
if len(row) == 2: # 确保每行有两列:文本和标签
data.append((row[0], row[1]))
return data
# 读取训练数据和测试数据
train_data = read_data_from_csv('train.csv')
test_data = read_data_from_csv('test.csv')
# ----------------------
# 2. 自定义特征提取器:
# ----------------------
# 创建一个特征提取器,结合多种特征
def combined_extractor(document):
"""
结合多种特征来提高分类器的性能:
单词的词性标注:提取每个单词及其词性标注结果。
单词的词干:提取每个单词的词干形式。
句子长度:提取句子的长度(单词数量)。
特定单词的存在性:检查某些特定单词是否出现在句子中
"""
blob = TextBlob(document)
feats = {}
# 1. 单词的词性标注
for word, pos in blob.tags:
feats[f"{word.lower()}_{pos}"] = True
# 2. 单词的词干
for word in blob.words:
feats[f"stem({word.stem()})"] = True
# 3. 句子长度
feats["sentence_length"] = len(blob.words)
# 4. 特定单词的存在性
specific_words = ["good", "bad", "amazing", "horrible", "love", "hate"]
for word in specific_words:
feats[f"contains({word})"] = word in blob.words
return feats
# ----------------------
# 3. 创建分类器:
# ----------------------
# 创建朴素贝叶斯分类器
# 将训练数据 + 特征提取器 传递给构造函数
cl = NaiveBayesClassifier(train_data, feature_extractor=combined_extractor)
# 创建决策树分类器
# 决策树分类器无法获取概率分布,而是直接给出分类结果
# cl = DecisionTreeClassifier(train_data)
# ----------------------
# 4. 使用分类器对文本进行分类:
# ----------------------
# 使用分类器对文本进行分类
blob = TextBlob("The beer is good. But the hangover is horrible.", classifier=cl)
# 使用分类器对文本进行分类
for s in blob.sentences:
print(f"文本: {s}")
print(f"预测类别: {s.classify()}")
# 使用prob_classify(text)方法获取标签的概率分布
prob_dist = cl.prob_classify(s.raw) # .raw属性用于获取句子的原始文本内容
print(f"Positive置信度: {round(prob_dist.prob('pos'), 2)}")
print(f"Negative置信度: {round(prob_dist.prob('neg'), 2)}")
print("------------------")
# ----------------------
# 5. 评估分类器:
# ----------------------
# 使用accuracy(test_data)方法,计算分类器在测试集上的准确率
cl.accuracy(test_data)
# 使用show_informative_features()方法显示最有信息量的特征列表
cl.show_informative_features(5)
# ----------------------
# 6. 使用新数据更新分类器:
# ----------------------
new_data = [("She is my best friend.", "pos"),
("I'm happy to have a new friend.", "pos"),
("Stay thirsty, my friend.", "pos"),
("He ain't from around here.", "neg"),
]
# 使用新数据更新分类器
cl.update(new_data)
cl.accuracy(test_data)


本篇文章来源于微信公众号: 码农设计师