python的文本分类

文本分类

分类器

分类器:特征选择 + 分类器模型

分类器的实现过程:

  1. 选择特征
  2. 训练
  3. 评估,错误分析,修改特征
  4. 重新训练在新的开发集上

有监督的文本分类器的举例

设计一个人名-性别分类器,可以依据名字判断性别。

特征选择:选择名字最后一个字母作为特征。特征集是词典{(特征名字: 特征值)}

import nltk
from nltk.corpus import names 
import random

names = [(name, 'male') for name in names.words('male.txt')] + [(name, 'female') for name in names.words('female.txt')]

random.shuffle(names) # 随机化

def gender_features(word): # 提取特征
	return {
    
    'last_letter': word[-1]}	
featuresets = [(gender_features(n), g) for (n,g) in names]

train_set, test_set = featuresets[:5000], featuresets[5000:] # 训练集和测试集

classifier = nltk.NaiveBayesClassifier.train(train_set) # 训练

# 结果:male
print(classifier.classify(gender_features('tom'))) # 预测
# 结果:0.7659646739130435
print(nltk.classify.accuracy(classifier, test_set)) # 评估

# 生成错误列表
errors = [ (tag, classifier.classify(gender_features(name)), name) for (name, tag) in names if classifier.classify(gender_features(name)) != tag]
print(errors)

电影评论语料库,其中的评论被分为正面和负面。选择特征为词表中前2000词的出现与否。

一. 数据准备
1.获得带标签的影评文档

```py
import nltk
import random
from nltk.corpus import movie_reviews

documents = [(list(movie_reviews.words(fileid)), category) for category in movie_reviews.categories() for fileid in movie_reviews.fileids(category)] # 转化为词列表的影评,与标签组成二元组
random.shuffle(documents) # 随机化
```

2.构建特征提取器

```py
all_words = nltk.FreqDist(w.lower() for w in movie_reviews.words())	# 建立全部影评的词频表
all_words=all_words.most_common(2000) # 词频表按频率排序
word_features  =[w for (w,f) in all_words] # 特征词为词频表中前2000词

def document_features(document): # 建立特征提取器,标定该影评是否有特征词
    document_words = set(document)
    features = {}
    for word in word_features:
    	features['contains(%s)' % word] = (word in document_words)
    return features
```

3.建立特征集

```py
featuresets = [(document_features(d), c) for (d,c) in documents]
train_set, test_set = featuresets[:1000], featuresets[1000:]
```

二.使用特征集训练分类器
py classifier = nltk.NaiveBayesClassifier.train(train_set)

三.使用分类器分类
py classifier.classify(test_set[0][0])

四.评估分类器
py nltk.classify.accuracy(classifier, test_set)
观察分类特征的贡献:
py classifier.show_most_informative_features(5)

朴素贝叶斯分类器

基本思想:在现有数据的条件下,选择最大概率的类。

基本假设:各个特征之间相互独立,每个特征与其他特征都不相关。

基于nltk的朴素贝叶斯分类器

# 同前例
classifier = nltk.NaiveBayesClassifier.train(train_set)
classifier.classify(test_set[0][0])
nltk.classify.accuracy(classifier, test_set)
classifier.show_most_informative_features(5)

猜你喜欢

转载自blog.csdn.net/xukeke12138/article/details/111602970