第一天学习进度--文本处理基础知识学习

参考教程--python机器学习基础教程

首先在对应目录创建一个文件夹,里面放上对应分类名称(非中文)的文件夹,这个步骤是要读取对应类型的数据。

结构如下图所示:

 

 我在txttype中放置了两个分类的文件夹,每个类别的文件夹中放置了对应类型的文本(数量不限),每个需要训练的语句都单独作为一个文本,文本的名称不做具体要求。

在python中写入对应的代码:

from sklearn.datasets import load_files
import numpy as np
#加载数据集
reviews_train = load_files(r"C:\Users\Halo\Desktop\1.6项目开发过程\txttype")
# load_files返回一个Bunch对象,其中包含训练文本和训练标签
text_train, y_train = reviews_train.data, reviews_train.target
print("文本序列类型: {}".format(type(text_train)))
print("文本序列长度: {}".format(len(text_train)))
# print("text_train[1]:\n{}".format(text_train[1]))
#数据清洗
text_train = [doc.replace(b"<br />", b" ") for doc in text_train]
print("每个类型的样本: {}".format(np.bincount(y_train)))
 

可以发现对应的文本文件已经被正确读取

 

 

 

 接着进行第二步,将文本数据转化为词袋

计算词袋在书中的步骤原话为:

计算词袋表示包括以下三个步骤。
(1) 分词(tokenization) 。将每个文档划分为出现在其中的单词 [ 称为词例(token)],比如 按空格和标点划分。

(2) 构建词表(vocabulary building)。收集一个词表,里面包含出现在任意文档中的所有词, 并对它们进行编号(比如按字母顺序排序)。

(3) 编码(encoding)。对于每个文档,计算词表中每个单词在该文档中的出现频次

 

 

 将上述的过程合并之后:

from sklearn.feature_extraction.text import CountVectorizer

bards_words =["The fool doth think he is wise,",
              "but the wise man knows himself to be a fool"]
#切词
vect = CountVectorizer()
vect.fit(bards_words)
print("Vocabulary size: {}".format(len(vect.vocabulary_)))
print("Vocabulary content:\n {}".format(vect.vocabulary_))
#词袋应用
bag_of_words = vect.transform(bards_words)
print("bag_of_words: \n{}".format(repr(bag_of_words.toarray())))

上述是对于该用法的简单应用,下面将配合参数调节对数据进行读取。

可以先获取前20个特征

#切词并获得词袋
vect = CountVectorizer().fit(text_train)
#应用词袋
X_train = vect.transform(text_train)
print("X_train:\n{}".format(repr(X_train)))

#获得文本特征
feature_names = vect.get_feature_names()
print("特征数量: {}".format(len(feature_names)))
print("前20个特征:\n{}".format(feature_names[:20]))

运行结果:

 接着对模型进行评估:

from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
#交叉验证对LogisticRegression进行评估
scores = cross_val_score(LogisticRegression(), X_train, y_train, cv=5)
print("平均交叉验证精度: {:.2f}".format(np.mean(scores)))

运行结果:

 

 

 在利用交叉验证调节正则化参数C:

#交叉验证调节正则化参数C
from sklearn.model_selection import GridSearchCV
param_grid = {'C': [0.001, 0.01, 0.1, 1, 10]}
grid = GridSearchCV(LogisticRegression(), param_grid, cv=5)
grid.fit(X_train, y_train)
print("最好的交叉验证分数: {:.2f}".format(grid.best_score_))
print("最好参数值: ", grid.best_params_)

运行结果:

 

 接下来将数据应用到实际的测试集合上上看看该性能指标:

#加载测试集
reviews_test = load_files(r"C:\Users\Halo\Desktop\1.6项目开发过程\txttest")
text_test, y_test = reviews_test.data, reviews_test.target
print("测试集数量: {}".format(len(text_test)))
print("文本序列长度: {}".format(np.bincount(y_test)))
text_test = [doc.replace(b"<br />", b" ") for doc in text_test]
#在测试集上评估参数泛化性能
X_test = vect.transform(text_test)
print("测试集评估参数泛化性能:{:.2f}".format(grid.score(X_test, y_test)))

运行结果:

 

 若数据过多,则可以对数据进行清洗:

#集合清洗
vect = CountVectorizer(min_df=5).fit(text_train)
X_train = vect.transform(text_train)
print("min_df: {}".format(repr(X_train)))
feature_names = vect.get_feature_names()
print("前50个特征:\n{}".format(feature_names[:50]))
#再次用玩个搜索看模型性能
grid = GridSearchCV(LogisticRegression(), param_grid, cv=5)
grid.fit(X_train, y_train)
print("最好交叉验证分数: {:.2f}".format(grid.best_score_))

运行结果:

 

posted on 2020-07-08 17:02  Halone  阅读(265)  评论(0编辑  收藏  举报