Sklearn和NLTK

1 实验介绍

1.1 关于本实验

本实验主要介绍Sklearn和NLTK两个重要的机器学习与自然语言处理库。其中,Sklearn是机器学习中常用的第三方模块,对常用的机器学习方法进行了封装,实现文本人类和聚类等功能。NLTK是自然语言处理最常用的Python库,具有语料库,支持文本分类等功能。

1.2 实验目的

了解Sklearn的基本功能及基于Sklearn的机器学习流程;了解NLTK的基本功能、语料库及文本分类;掌握Sklearn与NLTK的应用。

2 Sklearn

2.1 Sklearn 简介

Sklearn(Scikit-learn)是机器学习中常用的第三方模块,对常用的机器学习方法进行了封装,具有分类、回归、聚类、降维、模型选择、预处理六大模块。

(1)分类:识别某个对象属于哪个类别,常用的算法有SVM(支持向量机)、KNN(最近邻)、Random Forest(随机森林)。

(2)回归:预测与对象相关联的连续值属性,常见的算法有SVR(支持向量机)、Ridge Regression(岭回归)。

(3)聚类:将相似对象自动归类分组,常用的算法有K-Means(K均值聚类算法)。

(4)降维:减少要考虑的随机变量的数量,常见的算法有PCA(主成分分析)、Feature Selection(特征选择)。

(5)模型选择:用于比较、验证、选择参数和模型,常用的模块有Grid Search(网络搜索)、Cross Validation(交叉验证)、Metrics(度量)。

(6)预处理:用于特征提取和归一化,具有Preprocessing(预处理)和Feature Extraction特征提取模块。

Sklearn针对无监督学习算法具有如下模块:

算法说明算法说明
Cluster聚类neural_newwork无监督的神经网络
Decomposition因子分解Covariance协方差估计
Mixture高斯混合模型

Sklearn针对有监督学习算法具有如下模块:

算法说明算法说明
Tree决策树neural_network神经网络
SVM支持向量机kernel_ridge岭回归
Neighbors近邻算法naive_bayes朴素贝叶斯
linear_model广义线性模型

Sklearn针对数据转换具有如下模块:

模块说明
feature_extraction特征提取
feature_selection特征选择
preprocessing预处理

2.2 数据集

2.2.1 小数据集

机器学习领域有句话:“数据和特征决定了机器学习的上限,而模型和算法只是逼近这个上限而于。”数据作为机器学习的最关键要素,决定着模型选择、参数的设定和调优。Sklearn使用datasets模块导入数据集,代码如下:

from sklearn import datasets

Sklearn提供小数据集、大数据集和生成数据集三种数据集。

2.2.1.1 鸢尾花数据集

鸢尾花(iris)数据集是一种多重变量分析的数据集,该数据集包含150个数据样本,分为山鸢尾、变色鸢尾和弗吉尼亚鸢尾三类,鸢尾花数据集使用如下命令加载:

from sklearn.datasets import load_iris

【任务1】iris数据集

from sklearn.datasets import load_iris     #加载数据集
iris=load_iris()
n_samples,n_features=iris.data.shape
print(iris.data.shape)   #(150, 4)  表示为150个样本,4个特征
print(iris.target.shape)   #(150,)
print("特征值的名字:\n",iris.feature_names)   #特征名称
print("鸢尾花的数据集描述:\n",iris['DESCR'])    #数据描述

程序运行结果如下:

(150, 4)
(150,)
特征值的名字:
[‘sepal length (cm)’, ‘sepal width (cm)’, ‘petal length (cm)’, ‘petal width (cm)’]

2.2.1.2 手写数字数据集

手写数字数据集包括1297个09的手写数字数据,每个数字由8X8大小的矩阵构成,矩阵中值的范围是016,代表颜色的深度。手写数字数据集使用如下命令加载:

from sklearn.datasets import load_boston

【任务2】digits数据集

from sklearn.datasets import load_digits   #导入手写数字数据集
digits = load_digits()
print(digits.keys())
#一共有1797张图面,每张图面有64个像素点
print(digits.data)
print(digits.data.shape)
#从标签可以看出数据的范围是从0-9
print(digits.target)
print(digits.target.shape)
#图像信息以8*8的矩阵存储
print(digits.images)
print(digits.images.shape)

import matplotlib.pyplot as plt
plt.figure(figsize=(8,8))
for i in range(10):
    plt.subplot(1,10,i+1)  #图片是1*10的 参数(行数,列数,当前图片的序号)
    plt.imshow(digits.images[i],cmap="Greys")
    plt.xlabel(digits.target[i])
    plt.xticks([])
    plt.yticks([])  #去掉坐标轴
plt.show()

程序运行结果如下:

dict_keys([‘data’, ‘target’, ‘frame’, ‘feature_names’, ‘target_names’, ‘images’, ‘DESCR’])
[[ 0. 0. 5. … 0. 0. 0.]
[ 0. 0. 0. … 10. 0. 0.]
[ 0. 0. 0. … 16. 9. 0.]

[ 0. 0. 1. … 6. 0. 0.]
[ 0. 0. 2. … 12. 0. 0.]
[ 0. 0. 10. … 12. 1. 0.]]
(1797, 64)
[0 1 2 … 8 9 8]
(1797,)
[[[ 0. 0. 5. … 1. 0. 0.]
[ 0. 0. 13. … 15. 5. 0.]
[ 0. 3. 15. … 11. 8. 0.]

[ 0. 4. 11. … 12. 7. 0.]
[ 0. 2. 14. … 12. 0. 0.]
[ 0. 0. 6. … 0. 0. 0.]]

[[ 0. 0. 0. … 5. 0. 0.]
[ 0. 0. 0. … 9. 0. 0.]
[ 0. 0. 3. … 6. 0. 0.]

[ 0. 0. 1. … 6. 0. 0.]
[ 0. 0. 1. … 6. 0. 0.]
[ 0. 0. 0. … 10. 0. 0.]]

[[ 0. 0. 0. … 12. 0. 0.]
[ 0. 0. 3. … 14. 0. 0.]
[ 0. 0. 8. … 16. 0. 0.]

[ 0. 9. 16. … 0. 0. 0.]
[ 0. 3. 13. … 11. 5. 0.]
[ 0. 0. 0. … 16. 9. 0.]]

[[ 0. 0. 1. … 1. 0. 0.]
[ 0. 0. 13. … 2. 1. 0.]
[ 0. 0. 16. … 16. 5. 0.]

[ 0. 0. 16. … 15. 0. 0.]
[ 0. 0. 15. … 16. 0. 0.]
[ 0. 0. 2. … 6. 0. 0.]]

[[ 0. 0. 2. … 0. 0. 0.]
[ 0. 0. 14. … 15. 1. 0.]
[ 0. 4. 16. … 16. 7. 0.]

[ 0. 0. 0. … 16. 2. 0.]
[ 0. 0. 4. … 16. 2. 0.]
[ 0. 0. 5. … 12. 0. 0.]]

[[ 0. 0. 10. … 1. 0. 0.]
[ 0. 2. 16. … 1. 0. 0.]
[ 0. 0. 15. … 15. 0. 0.]

[ 0. 4. 16. … 16. 6. 0.]
[ 0. 8. 16. … 16. 8. 0.]
[ 0. 1. 8. … 12. 1. 0.]]]
(1797, 8, 8)

在这里插入图片描述

2.3 大数据集

大数据集使用sklearn.datasets fetch_*导入,第一次使用时会自动下载,Sklearn的大数据集如下:

API函数中文翻译任务类型
fetch_olivetti_facesOlivetti面部图像数据集降维
fetch_20newsgroups新闻分类数据集分类
fetch_lfw_people带标签的人脸数据集分类,降维
fetch_rcvl路透社英文新闻文本分类数据集分类

其中,20newsgroups数据集共有18000篇新闻文章,涉及20种话题,所以称作20newsgroups text dataset,是文本分类、文本挖掘和信息检索研究的国际标准数据集之一。加载20newsgroups数据集有如下两种方式:

(1)sklearn.datasets.fetch_20newsgroups:返回一个可以被文本特征提取器自定义参数提取特征的原始文本序列。

(2)sklearn.datasets.fetch_20newsgroups_vectorized:返回一个已提取特征的文本序列,即不需要使用特征提取器。

【任务3】使用20newsgroups数据集

from sklearn.datasets import fetch_20newsgroups   #加载数据集
news = fetch_20newsgroups()
print(len(news.data))  
print(news.target.shape)  
print("数据集描述:\n",news['DESCR'])

程序运行结果如下:

11314
(11314,)

2.4 生成数据集

Scikit_learn采用sklearn.datasets.make_*创建数据集,用来生成适合特定机器学习模型的数据。常用的API如下:

API函数名功能
make_regression生成回归模型的数据
make_blobs生成聚类模型数据
make_classification生成分类模型数据
make_gaussian_quantiles生成分组多维正态分布的数据
make_circles生成环线数据

2.4.1 make_regression

sklearn.datasets.samples_generator模块提供make_regression()函数,语法形式如下:

make_regression(n_samples,n_features,noise,coef)

参数解释如下:

(1)n_samples:生成样本数。

(2)n_features:样本特征数。

(3)noise:样本随机噪声。

(4)coef:是否返回回归系数。

【任务4】make_regression实例

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_regression
# X为样本特征,y为样本输出, coef为回归系数,共1000个样本,每个样本1个特征
X, y, coef =make_regression(n_samples=1000, n_features=1,noise=10, coef=True)
# 画图
plt.scatter(X, y,  color='black')
plt.plot(X, X*coef, color='blue', linewidth=3)
plt.xticks(())
plt.yticks(())
plt.show()

在这里插入图片描述

2.4.2 make_blobs

sklearn.datasets.make_blobs()可以根据用户指定的特征数理、中心点数量、范围等生成数据,用于测试聚类算法。make_blobs()函数语法如下:

sklearn.datasets.make_blobs(n_samples,n_features,centers,cluster_sld)

参数解释如下:

(1)n_samples:生成样本数。

(2)n_features:样本特征数。

(3)centers:簇中心的个数或者自定义的簇中心。

(4)cluster_sld:簇数据方差,代表簇的聚合程度。

【任务5】make_blobs实例

import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
X, y = make_blobs(n_samples=50, centers=2,random_state=50,cluster_std=2)
plt.scatter(X[:, 0], X[:, 1], c=y,cmap=plt.cm.cool)
plt.show()

在这里插入图片描述

2.4.3 make_classification

make_classification()生成分类模型数据,语法形式如下:

make_classification(n_samples,n_features,n_redundant,n_classes,random_state)

参数解释如下:

(1)n_samples:指定样本数。

(2)n_features:指定特征数。

(3)n_redundant:冗余特征数。

(4)n_classes:指定几分类。

(5)random_state:随机种子。

【任务6】make_classification实例

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
# X1为样本特征,Y1为样本类别输出, 共400个样本,每个样本2个特征,输出有3个类别,没有冗余特征,每个类别一个簇
X1, Y1 = make_classification(n_samples=400, n_features=2, n_redundant=0,
                             n_clusters_per_class=1, n_classes=3)
plt.scatter(X1[:, 0], X1[:, 1], marker='o', c=Y1)
plt.show()

在这里插入图片描述

2.4.4 make_gaussian_quantiles

make_gaussian_quantiles()方法用于生成分组多维正态分布的数据,语法形式如下:

make_gaussian_quantiles(mean,cov,n_samples,n_features,n_classes)

参数解释如下:

(1)n_samples:指定样本数。

(2)n_features:指定特征数。

(3)mean:特征均值。

(4)cov:样本协分差的系数。

(5)n_classes:数据在正态分布中按分位数分配的组数。

【任务7】make_gaussian_quantiles实例

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_gaussian_quantiles
#生成2维正态分布,数据按分位数分成3组,1000个样本,2个样本特征均值为1和2,协方差系数为2
X1, Y1 = make_gaussian_quantiles(n_samples=1000, n_features=2, n_classes=3, mean=[1,2],cov=2)
plt.scatter(X1[:, 0], X1[:, 1], marker='o', c=Y1)
<matplotlib.collections.PathCollection at 0x7f50594fb6d0>

在这里插入图片描述

2.4.5 make_circles

make_circles()可以为数据集添加噪声,为二元分类器产生环线数据,语法形式如下:

make_circles(n_samples,noise,factor)

参数解释如下:

(1)n_samples:指定样本数。

(2)noise:样本随机噪声。

(3)factor:内外圆之间的比例因子。

【任务8】make_circles实例

#生成球形判决界面的数据
from sklearn.datasets import make_circles
X,labels=make_circles(n_samples=200,noise=0.2,factor=0.2)
print("X.shape:",X.shape)
print("labels:",set(labels))

unique_lables=set(labels)
colors=plt.cm.Spectral(np.linspace(0,1,len(unique_lables)))
for k,col in zip(unique_lables,colors):
    x_k=X[labels==k]
    plt.plot(x_k[:,0],x_k[:,1],'o',markerfacecolor=col,markeredgecolor="k",markersize=14)
plt.title('data by make_moons()')
plt.show()

X.shape: (200, 2)
labels: {0, 1}

在这里插入图片描述

2.5 机器学习流程

基于Sklearn的机器学习流程包括语料清洗、划分数据集、特征工程、机器算法和模型评估等步骤。

2.5.1 语料清洗

数据集中往往存在大量异常值、缺失值等“脏”数据,一般采用Pandas库进行数据处理,Sklearn中Imputer类或SimpleImputer类也可以处理缺失值。

2.5.2 划分数据集

在机器学习中,通常将数据集划分为训练数据集和测试数据集。训练数据集用于训练数据,生成机器学习模型。测试数据集用于验证生成的机器学习模型的效果如何,数据划分方法一般有留出法、交叉验证法和自助法等。

2.5.2.1 留出法

留出法将数据集分成训练和测试两个互斥的部分。

留出法具有如下优点:

(1)实现简单、方便,在一定程度上能评估泛化误差。

(2)测试集和训练集分开,缓解了过拟合。

留出法具有如下缺点:

(1)数据都只被使用了一次,没有被充分利用。

(2)在验证集上计算出来的最后的评估指标与原始分组有很大关系。

(3)稳定性较差,通常会进行若干次随机划分,重复评估取平均值作为评估结果。

一般情况下,数据划分训练集占70%80%,测试集占20%30%。Sklearn提供train_test_split()函数,语法形式如下:

x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(train_data, train_target, test_size, random_state)

参数解释如下:

(1)train_data:待划分的样本数据。

(2)train_target:待划分样本数据的结果(标签)。

(3)test_size:样本标签。

(4)random_state:设置随机种子,保证每次都是同一个随机。若为0或不真,生成的随机数不同。

(5)x_train:划分出的训练集数据(特征值)。

(6)x_test:划分出的测试集数据(特征值)。

(7)y_train:划分出的训练集标签(目标值)。

(8) y_test:划分出的测试集标签(目标值)。

【任务9】数据集拆分实例

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split    
# 获取鸢尾花数据集
iris = load_iris()
# test_size 默认取值为 25%,test_size取值为0.2 ,随机种子 22
x_train, x_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=22)
print("训练集的特征值:\n",x_train,x_train.shape)

训练集的特征值:
[[4.8 3.1 1.6 0.2]
[5.4 3.4 1.5 0.4]
[5.5 2.5 4. 1.3]
[5.5 2.6 4.4 1.2]
[5.7 2.8 4.5 1.3]
[5. 3.4 1.6 0.4]
[5.1 3.4 1.5 0.2]
[4.9 3.6 1.4 0.1]
[6.9 3.1 5.4 2.1]
[6.7 2.5 5.8 1.8]
[7. 3.2 4.7 1.4]
[6.3 3.3 4.7 1.6]
[5.4 3.9 1.3 0.4]
[4.4 3.2 1.3 0.2]
[6.7 3. 5. 1.7]
[5.6 3. 4.1 1.3]
[5.7 2.5 5. 2. ]
[6.5 3. 5.8 2.2]
[5. 3.6 1.4 0.2]
[6.1 2.8 4. 1.3]
[6. 3.4 4.5 1.6]
[6.7 3. 5.2 2.3]
[5.7 4.4 1.5 0.4]
[5.4 3.4 1.7 0.2]
[5. 3.5 1.3 0.3]
[4.8 3. 1.4 0.1]
[5.5 4.2 1.4 0.2]
[4.6 3.6 1. 0.2]
[7.2 3.2 6. 1.8]
[5.1 2.5 3. 1.1]
[6.4 3.2 4.5 1.5]
[7.3 2.9 6.3 1.8]
[4.5 2.3 1.3 0.3]
[5. 3. 1.6 0.2]
[5.7 3.8 1.7 0.3]
[5. 3.3 1.4 0.2]
[6.2 2.2 4.5 1.5]
[5.1 3.5 1.4 0.2]
[6.4 2.9 4.3 1.3]
[4.9 2.4 3.3 1. ]
[6.3 2.5 4.9 1.5]
[6.1 2.8 4.7 1.2]
[5.9 3.2 4.8 1.8]
[5.4 3.9 1.7 0.4]
[6. 2.2 4. 1. ]
[6.4 2.8 5.6 2.1]
[4.8 3.4 1.9 0.2]
[6.4 3.1 5.5 1.8]
[5.9 3. 4.2 1.5]
[6.5 3. 5.5 1.8]
[6. 2.9 4.5 1.5]
[5.5 2.4 3.8 1.1]
[6.2 2.9 4.3 1.3]
[5.2 4.1 1.5 0.1]
[5.2 3.4 1.4 0.2]
[7.7 2.6 6.9 2.3]
[5.7 2.6 3.5 1. ]
[4.6 3.4 1.4 0.3]
[5.8 2.7 4.1 1. ]
[5.8 2.7 3.9 1.2]
[6.2 3.4 5.4 2.3]
[5.9 3. 5.1 1.8]
[4.6 3.1 1.5 0.2]
[5.8 2.8 5.1 2.4]
[5.1 3.5 1.4 0.3]
[6.8 3.2 5.9 2.3]
[4.9 3.1 1.5 0.1]
[5.5 2.3 4. 1.3]
[5.1 3.7 1.5 0.4]
[5.8 2.7 5.1 1.9]
[6.7 3.1 4.4 1.4]
[6.8 3. 5.5 2.1]
[5.2 2.7 3.9 1.4]
[6.7 3.1 5.6 2.4]
[5.3 3.7 1.5 0.2]
[5. 2. 3.5 1. ]
[6.6 2.9 4.6 1.3]
[6. 2.7 5.1 1.6]
[6.3 2.3 4.4 1.3]
[7.7 3. 6.1 2.3]
[4.9 3. 1.4 0.2]
[4.6 3.2 1.4 0.2]
[6.3 2.7 4.9 1.8]
[6.6 3. 4.4 1.4]
[6.9 3.1 4.9 1.5]
[4.3 3. 1.1 0.1]
[5.6 2.7 4.2 1.3]
[4.8 3.4 1.6 0.2]
[7.6 3. 6.6 2.1]
[7.7 2.8 6.7 2. ]
[4.9 2.5 4.5 1.7]
[6.5 3.2 5.1 2. ]
[5.1 3.3 1.7 0.5]
[6.3 2.9 5.6 1.8]
[6.1 2.6 5.6 1.4]
[5. 3.4 1.5 0.2]
[6.1 3. 4.6 1.4]
[5.6 3. 4.5 1.5]
[5.1 3.8 1.5 0.3]
[5.6 2.8 4.9 2. ]
[4.4 3. 1.3 0.2]
[5.5 2.4 3.7 1. ]
[4.7 3.2 1.6 0.2]
[6.7 3.3 5.7 2.5]
[5.2 3.5 1.5 0.2]
[6.4 2.7 5.3 1.9]
[6.3 2.8 5.1 1.5]
[4.4 2.9 1.4 0.2]
[6.1 3. 4.9 1.8]
[4.9 3.1 1.5 0.2]
[5. 2.3 3.3 1. ]
[4.8 3. 1.4 0.3]
[5.8 4. 1.2 0.2]
[6.3 3.4 5.6 2.4]
[5.4 3. 4.5 1.5]
[7.1 3. 5.9 2.1]
[6.3 3.3 6. 2.5]
[5.1 3.8 1.9 0.4]
[6.4 2.8 5.6 2.2]
[7.7 3.8 6.7 2.2]] (120, 4)

2.5.2.2 K折交叉验证

当数据集较大,采用K折交叉验证。K折是指将数据集进行K次分割,使得所有数据在训练集和测试集中都出现,但每次分割不会重叠,相当于无放回抽样。

KFold()函数语法形式如下:

KFold(n_splits,shuffle,random_state)

参数解释如下:

(1)n_splits:表示划分为几等份(至少是2)。

(2)shuffle:表示是否进行洗牌,即是否打乱划分,默认为False,即不打乱。

(3)random_state:随机种子数。

方法:

(1)get_n_splits([X,y,groups]):获取参数n_splits的值。

(2)splits(X[,y,groups]):将数据集划分成训练集和测试集,返回索引生成器。

【任务10】Kfold实例

import numpy as np  
from sklearn.model_selection import KFold
X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
kf = KFold(n_splits=2)
print( kf.get_n_splits(X))
for train_index, test_index in kf.split(X):
    print("TRAIN:", train_index, "TEST:", test_index)

程序运行结果如下:

2
TRAIN: [2 3] TEST: [0 1]
TRAIN: [0 1] TEST: [2 3]

2.5.2.3 分层交叉验证

Sklearn提供cross_val_score()函数将数据集划分为K个大小相似的互斥子集,每次用K-1个子集作为训练集,余下人个子集作为测试集,如此反复循环,进行K次训练和测试,返回K个测试结果的均值。基中,“10次10折交叉验证法”最为常用,将数据集分成10份,轮流将9份数据作为训练集,1份数据作为测试集。

cross_val_score()函数语法形式如下:

cross_val_score(estimator,train_x,train_y,cv=10)

参数解释如下:

(1)estimator:需要使用交叉验证的算法。

(2)train_x:输入样本数据。

(3)train_y:样本标签。

(4)cv=10:默认使用Kfold()进行数据集打乱。

【任务11】利用交叉验证实例

from sklearn import datasets     
from sklearn.model_selection import train_test_split,cross_val_score    #划分数据交叉验证
from sklearn.neighbors import KNeighborsClassifier     
import matplotlib.pyplot as plt
iris = datasets.load_iris()      #加载iris数据集
X = iris.data 
y = iris.target         #这是每个数据所对应的标签
train_X,test_X,train_y,test_y = train_test_split(X,y,test_size=1/3,random_state=3)  # 以1/3划分训练集 训练结果 测试集测试结果
k_range = range(1,31)
cv_scores = []      #用来放每个模型的结果值
for n in k_range:
    knn = KNeighborsClassifier(n)   
    scores = cross_val_score(knn,train_X,train_y,cv=10)   
    cv_scores.append(scores.mean())
plt.plot(k_range,cv_scores)
plt.xlabel('K')
plt.ylabel('Accuracy')      #通过图像选择最好的参数
plt.show()
best_knn = KNeighborsClassifier(n_neighbors=3)     # 选择最优的K=3传入模型
best_knn.fit(train_X,train_y)              #训练模型
print("score:\n",best_knn.score(test_X,test_y)) #看看评分

在这里插入图片描述

score:
0.94

2.5.2.4 自助法

与K折交叉验证相经自助法(Bootstrapping)的实质是有放回的随机抽样,将记录用于测试集后,放回数据集,继续下一次随机抽样,直到测试集中的数据条数满足要求。

ShuffleSplit()函数语法形式如下:

ShuffleSplit(n_splits, test_size, train_size,random_state)

参数解释如下:

(1)n_splits:表示划分为几块(至少是2)。

(2) test_size:测试集比例或样本数量。

(3)train_size:样训练集比例或样本数量。

(4)random_state:随机种子数,默认为None。

【任务12】ShuffleSplit实例

import numpy as np 
from sklearn.model_selection import ShuffleSplit
X = np.arange(5)
ss = ShuffleSplit(n_splits=3, test_size=.25, random_state=0)
for train_index, test_index in ss.split(X):
    print("TRAIN:", train_index, "TEST:", test_index) 

程序运行结果如下:

TRAIN: [1 3 4] TEST: [2 0]
TRAIN: [1 4 3] TEST: [0 2]
TRAIN: [4 0 2] TEST: [1 3]

2.5.3 特征工程

特征工程用于从原始数据中提取特征以供算法和模型使用。Sklearn提供了较为完整的特征处理方法,包括数据预处理、特征选择、降维等,相关函数如下:

功能说明
StandardScaler无量纲化标准化,将特征值转换至服从标准正态分布
MinMaxScaler无量纲化区间缩放,基于最大最小值,将特征值转换到[0,1]区间上
Normalizer归一化基于特征矩阵的行,将样本向量转换为“单位向量”
Binarizer二值化基于给定阈值,将定量特征按阈值划分
OneHotEncoder哑编码将定性数据编码为定量数据
Imputer缺失值计算计算缺失值,缺失值可填充为均值等

2.5.4 机器算法

Sklearn提供传的机器学习算法实现分类和聚类,采用支持向量机、朴素贝叶斯等算法实现文本分类,采用K-Means算法实习文本聚类。例如,支持向量机的代码如下:

from sklearn.svm import svc #支持向量机

estimator=svc()

estimator.rit(x_train,y_train) #训练集的特征值与目标值

2.5.5 模型评估

通过计算混淆矩阵、精确率、召回率和F-score等进行分类评估。

方法1:计算出准确率。

score=estimator.score(x_test,y_test) #测试集的特征值和目标值

print(score)

方法2:对比预测值与真实值

y_ptedict=estimator.predict(x_test) #预测

print(“对比真实值和预测值\n”,y_test==y_predict)

3 NLTK

3.1 NLTK简介

NLTK被 称为“使用Python进行教学和计算语言学工作的绝佳工具”“用自然语言进行游戏的神奇图书馆”,NLTK功能模块如下:

语言处理任务NLTK模块功能描述
获取和处理语料库nltk.cotpus语料库和词典的标准化接口
字符串nltk.tokenize,nltk.stem分词,句子分解提取主干
搭配发现nltk.collocationst-检验,卡方,点互信息PMI
词性标识符nltk.tagn-gram,backkff,Brill,HMM,TnT
分类nltk.classify,nltk.cluster决策树,最大熵,贝叶斯,EM,K-Means
分块nltk.chunk正则表达式,N-gram,命名实体
解析nltk.parse图表,基于特征,一致性,概率,依赖
语义解释nltk.sem,nltk.inference演算,一阶逻辑,模型检验
指标评测nltk.metrics精度,召回率,协议系数
概率与估计nltk.probability频率分布,平滑概率分布
应用nltk.app,nltk.chat图形化的关键词排序,聊天机器人
语言学领域nltk.toolbox处理SIL工具箱格式的数据

3.2 NLTK语料库

NLTK语料库有古腾堡语料库(gutenberg)、网络聊天语料库(webtext,nps_chat)、布朗语料库(brown)、路透社语料库(reuters)、就职演讲语料库(inaugural)等。

3.2.1 gutenberg语料库

gutenberg语料库包含古腾堡项目电子文档的一小部分文本。该项目大约有36000本免费文本,可以通过平均句子长度和平均词种数(词语丰富度)两个特征,分析不同作者的写作风格。

加载 NLTK 包并导入语料库,代码如下。

from nltk.corpus import inaugural
print(inaugural.fileids())

程序运行结果如下:

[‘1789-Washington.txt’, ‘1793-Washington.txt’, ‘1797-Adams.txt’, ‘1801-Jefferson.txt’, ‘1805-Jefferson.txt’, ‘1809-Madison.txt’, ‘1813-Madison.txt’, ‘1817-Monroe.txt’, ‘1821-Monroe.txt’, ‘1825-Adams.txt’, ‘1829-Jackson.txt’, ‘1833-Jackson.txt’, ‘1837-VanBuren.txt’, ‘1841-Harrison.txt’, ‘1845-Polk.txt’, ‘1849-Taylor.txt’, ‘1853-Pierce.txt’, ‘1857-Buchanan.txt’, ‘1861-Lincoln.txt’, ‘1865-Lincoln.txt’, ‘1869-Grant.txt’, ‘1873-Grant.txt’, ‘1877-Hayes.txt’, ‘1881-Garfield.txt’, ‘1885-Cleveland.txt’, ‘1889-Harrison.txt’, ‘1893-Cleveland.txt’, ‘1897-McKinley.txt’, ‘1901-McKinley.txt’, ‘1905-Roosevelt.txt’, ‘1909-Taft.txt’, ‘1913-Wilson.txt’, ‘1917-Wilson.txt’, ‘1921-Harding.txt’, ‘1925-Coolidge.txt’, ‘1929-Hoover.txt’, ‘1933-Roosevelt.txt’, ‘1937-Roosevelt.txt’, ‘1941-Roosevelt.txt’, ‘1945-Roosevelt.txt’, ‘1949-Truman.txt’, ‘1953-Eisenhower.txt’, ‘1957-Eisenhower.txt’, ‘1961-Kennedy.txt’, ‘1965-Johnson.txt’, ‘1969-Nixon.txt’, ‘1973-Nixon.txt’, ‘1977-Carter.txt’, ‘1981-Reagan.txt’, ‘1985-Reagan.txt’, ‘1989-Bush.txt’, ‘1993-Clinton.txt’, ‘1997-Clinton.txt’, ‘2001-Bush.txt’, ‘2005-Bush.txt’, ‘2009-Obama.txt’, ‘2013-Obama.txt’, ‘2017-Trump.txt’, ‘2021-Biden.txt’]

【任务13】gutenberg语料库实例

# 打开“古腾堡圣经”,阅读前几行
from nltk.tokenize import PunktSentenceTokenizer
from nltk.corpus import gutenberg
punkt_tokenizer = PunktSentenceTokenizer()
sample = gutenberg.raw("bible-kjv.txt")
tok = punkt_tokenizer.tokenize(sample)
for x in range(5):
    print(tok[x])

程序运行结果如下:

[The King James Bible]

The Old Testament of the King James Bible

The First Book of Moses: Called Genesis

1:1 In the beginning God created the heaven and the earth.
1:2 And the earth was without form, and void; and darkness was upon
the face of the deep.
And the Spirit of God moved upon the face of the
waters.
1:3 And God said, Let there be light: and there was light.
1:4 And God saw the light, that it was good: and God divided the light
from the darkness.

3.2.2 movie_reviews语料库

movie_reviews语料库拥有评论,被标记为正面或负面。

【任务14】movie_reviews语料库实例

import nltk
import random
from nltk.corpus import movie_reviews
#选取所有的文件 ID(每个评论有自己的 ID),然后对文件 ID存储word_tokenized版本(单词列表),后面是一个大列表中的正面或负面标签。
documents = [(list(movie_reviews.words(fileid)), category)
             for category in movie_reviews.categories()
             for fileid in movie_reviews.fileids(category)]
random.shuffle(documents)   #打乱文件进行训练和测试
#列表中第一个元素是一列单词,第二个元素是pos或neg标签。
#print(documents[1])    
all_words = []
for w in movie_reviews.words():
    all_words.append(w.lower())
all_words = nltk.FreqDist(all_words)    #单词频率分布
print(all_words.most_common(15))    #找出了15个最常用的单词
print(all_words["stupid"])   #某个单词的出现次数

程序运行结果如下:

[(‘,’, 77717), (‘the’, 76529), (‘.’, 65876), (‘a’, 38106), (‘and’, 35576), (‘of’, 34123), (‘to’, 31937), (“'”, 30585), (‘is’, 25195), (‘in’, 21822), (‘s’, 18513), (‘"’, 17612), (‘it’, 16107), (‘that’, 15924), (‘-’, 15595)]
253

3.3 NLTK文本分类

3.3.1 分句分词

NLTK提供nltk.sent_tokenize对文本按照句子进行分隔,使用nltk.word_tokenize将句子按照单词进行分隔,返回一个列表。

【任务15】分句分词实例

from nltk.tokenize import sent_tokenize, word_tokenize
EXAMPLE_TEXT = "Hello Mr. Smith, how are you doing today? The weather is great, and Python is awesome. The sky is pinkish-blue. You shouldn't eat cardboard."
print(sent_tokenize(EXAMPLE_TEXT))
print(word_tokenize(EXAMPLE_TEXT))

程序运行结果如下:
[‘Hello Mr. Smith, how are you doing today?’, ‘The weaher is great, and Python is awesome.’, ‘The sky is pinkish-blue.’, “You shouldn’t eat cardboard.”]
[‘Hello’, ‘Mr.’, ‘Smith’, ‘,’, ‘how’, ‘are’, ‘you’, ‘doing’, ‘today’, ‘?’, ‘The’, ‘weather’, ‘is’, ‘great’, ‘,’, ‘and’, ‘Python’, ‘is’, ‘awesome’, ‘.’, ‘The’, ‘sky’, ‘is’, ‘pinkish-blue’, ‘.’, ‘You’, ‘should’, “n’t”, ‘eat’, ‘cardboard’, ‘.’]

3.3.2 停止词

使用nltk.corpus的stopwords模块查看英文中的停止词表。

【任务16】停止词实例

from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
print(set(stopwords.words('english')))

example_sent = "This is a sample sentence, showing off the stop words filtration."
stop_words = set(stopwords.words('english'))
word_tokens = word_tokenize(example_sent)
filtered_sentence = [w for w in word_tokens if not w in stop_words]
filtered_sentence = []
for w in word_tokens:
    if w not in stop_words:
        filtered_sentence.append(w)
print(example_sent)
print("分词结果:\n",word_tokens)
print("添加停用词后的分词结果:\n",filtered_sentence)

程序运行结果如下:
{‘how’, ‘now’, ‘t’, ‘from’, ‘s’, ‘off’, ‘her’, ‘do’, ‘his’, ‘did’, ‘we’, ‘nor’, ‘other’, ‘a’, ‘your’, ‘who’, ‘same’, ‘you’, ‘most’, ‘having’, ‘our’, ‘again’, ‘some’, ‘each’, ‘were’, ‘only’, ‘out’, ‘hers’, ‘up’, ‘are’, ‘so’, ‘and’, ‘further’, ‘yourselves’, ‘my’, ‘myself’, ‘here’, ‘will’, ‘she’, ‘through’, ‘those’, ‘does’, ‘not’, ‘these’, ‘herself’, ‘yours’, ‘am’, ‘should’, ‘until’, ‘than’, ‘whom’, ‘had’, ‘which’, ‘don’, ‘doing’, ‘under’, ‘once’, ‘this’, ‘where’, ‘few’, ‘they’, ‘both’, ‘while’, ‘very’, ‘what’, ‘by’, ‘against’, ‘all’, ‘about’, ‘being’, ‘for’, ‘own’, ‘when’, ‘because’, ‘ours’, ‘down’, ‘on’, ‘with’, ‘or’, ‘i’, ‘was’, ‘it’, ‘him’, ‘to’, ‘before’, ‘them’, ‘such’, ‘if’, ‘between’, ‘after’, ‘is’, ‘the’, ‘theirs’, ‘has’, ‘at’, ‘yourself’, ‘have’, ‘then’, ‘ourselves’, ‘me’, ‘into’, ‘been’, ‘any’, ‘itself’, ‘he’, ‘be’, ‘no’, ‘too’, ‘more’, ‘themselves’, ‘can’, ‘in’, ‘there’, ‘during’, ‘of’, ‘its’, ‘but’, ‘below’, ‘just’, ‘why’, ‘as’, ‘above’, ‘that’, ‘himself’, ‘over’, ‘their’, ‘an’}

This is a sample sentence, showing off the stop words filtration.
分词结果:
[‘This’, ‘is’, ‘a’, ‘sample’, ‘sentence’, ‘,’, ‘showing’, ‘off’, ‘the’, ‘stop’, ‘words’, ‘filtration’, ‘.’]
添加停用词后的分词结果:
[‘This’, ‘sample’, ‘sentence’, ‘,’, ‘showing’, ‘stop’, ‘words’, ‘filtration’, ‘.’]

3.3.3 词干提取

词干提取是去除词缀得到词根的过程。例如,“fishing"“fished”"fish"和"fisher"为同一个词干”fish“。NLTK提供PorterStemmer进行词干提取。

【任务17】词干提取实例

from nltk.stem import PorterStemmer               
from nltk.tokenize import sent_tokenize, word_tokenize
ps = PorterStemmer()
example_words = ["python","pythoner","pythoning","pythoned","pythonly"]
print(example_words)
for w in example_words:
	print(ps.stem(w),end=' ')

程序运行结果如下:
[‘python’, ‘pythoner’, ‘pythoning’, ‘pythoned’, ‘pythonly’]
python python python python pythonli

3.3.4 词形还原

与词干提取非常类似的操作称为词形还原。词干提取经常可能创造出不存在的词汇,而词形还原的是实际的词汇。NLTK提供WordNetLemmatizer进行词干还原。

【任务18】词形还原实例

from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
print("cats\t",lemmatizer.lemmatize("cats"))
print("cacti\t",lemmatizer.lemmatize("cacti"))
print("geese\t",lemmatizer.lemmatize("geese"))
print("rocks\t",lemmatizer.lemmatize("rocks"))
print("python\t",lemmatizer.lemmatize("python"))
print("better\t",lemmatizer.lemmatize("better", pos="a"))
print("best\t",lemmatizer.lemmatize("best"))
print("ran\t",lemmatizer.lemmatize("ran",'v'))

程序运行结果如下:
cats cat
cacti cactus
geese goose
rocks rock
python python
better good
best best
ran run

3.3.5 同义词与反义词

NLTK提供WordNet进行定义词同义词、反义词等词汇数据库的集合。

【任务19】WordNet实例

from nltk.corpus import wordnet
#单词boy寻找同义词
syns = wordnet.synsets("boy")
print(syns[0].name())
#只是单词
print(syns[0].lemmas()[0].name())
#第一个同义词的定义
print(syns[0].definition())
#单词boy的使用示例
print(syns[0].examples())

程序运行结果如下:
male_child.n.01
male_child
a youthful male person
[‘the baby was a boy’, ‘she made the boy brush his teeth every night’, ‘most soldiers are only boys in uniform’]

【任务20】词形的近义词与反义词实例

from nltk.corpus import wordnet
synonyms = []              #. synonyms找到词形的近义词
antonyms = []                #.antonyms找到词形的反义词
for syn in wordnet.synsets("good"):
    for l in syn.lemmas():
        synonyms.append(l.name())
        if l.antonyms():
            antonyms.append(l.antonyms()[0].name())

print(set(synonyms))
print(set(antonyms))

程序运行结果如下:
{‘effective’, ‘undecomposed’, ‘commodity’, ‘well’, ‘sound’, ‘skilful’, ‘upright’, ‘practiced’, ‘unspoiled’, ‘safe’, ‘expert’, ‘thoroughly’, ‘serious’, ‘estimable’, ‘dependable’, ‘in_effect’, ‘unspoilt’, ‘secure’, ‘skillful’, ‘beneficial’, ‘respectable’, ‘honorable’, ‘near’, ‘trade_good’, ‘honest’, ‘salutary’, ‘proficient’, ‘in_force’, ‘just’, ‘soundly’, ‘full’, ‘adept’, ‘dear’, ‘good’, ‘goodness’, ‘right’, ‘ripe’}
{‘ill’, ‘bad’, ‘evilness’, ‘evil’, ‘badness’}

3.3.6 语义相关性

wordnet的wup_similarity()方法用于语义相关性

【任务21】语义相关性实例

from nltk.corpus import wordnet
w1 = wordnet.synset('ship.n.01')
w2 = wordnet.synset('boat.n.01')
print(w1.wup_similarity(w2))

w1 = wordnet.synset('ship.n.01')
w2 = wordnet.synset('car.n.01')
print(w1.wup_similarity(w2))

w1 = wordnet.synset('ship.n.01')
w2 = wordnet.synset('cat.n.01')
print(w1.wup_similarity(w2))

程序运行结果如下:
0.9090909090909091
0.6956521739130435
0.32

  • 15
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值