sklearn学习笔记(二)

1. sklearn中的一些函数

1.1make_blobs()

make_blobs() 函数生成带标签的数据集 生成分类和聚类数据

data, label = make_blobs(n_features=2, n_samples=100, centers=3,random_state=3,cluster_std=[0.8,2,5])
  • n_features 表示每一个样本有多少特征值
  • n_samples 表示样本的个数
  • centers 是聚类中心点的个数,可以理解为label的种类数
  • random_state 是随机种子,可以固定生成的数据
  • cluster_std 设置每个类别的方差, 默认为1

示例:

#导入数据集生成器
from sklearn.datasets import make_blobs

#生成样本数为200,分类为2的数据集
data = make_blobs(n_samples=200,centers=2,random_state=8)
print(data)

#想知道更多参数和细节用help命令查看,本文中其它函数也适用
help(make_blobs)

可以用这些数据绘制一个散点图:

X, y = data

import matplotlib.pyplot as plt

%matplotlib inline
#c = y: 颜色用类别区分, edgecolors: 是设置外圈颜色
plt.scatter(X[:, 0], X[:, 1],c=y,cmap=plt.cm.spring,edgecolors='k')

运行结果:
散点图


1.2 MinMaxScaler()、MaxAbsScaler()

MinMaxScaler()将数据缩放至指定范围内;

MaxAbsScaler()将数据的最大值缩放至1,范围是[0.1]

sklearn.preprocessing.MinMaxScaler(feature_range = (0,1),copy=True) 
sklearn.preprocessing.MaxAbsScaler(copy=True) 

示例:
先导入数据集

#导入boston数据集
from sklearn.datasets import load_boston
boston = load_boston()
boston

#导入iris数据集
from sklearn.datasets import load_iris
iris = load_iris()
iris
#将boston数据变换到(10, 100)
from sklearn.preprocessing import MinMaxScaler
mms = MinMaxScaler(feature_range=(10,100))

mms.fit(boston.data)
boston_mms = mms.transform(boston.data)

此时查看boston.data,原始数据并未发生变化,因为copy=True,在一个创建的新副本mms上做修改

mms2 = MinMaxScaler(feature_range=(10,100), copy=False)
mms2.fit_transform(boston.data)

执行后发现,原始数据和mms2相同。因为copy=True时并没有创建新副本,而是直接在原始数据上进行修改

2. 数据的normalization——向量单位化

2.1 正则化(Normalization)

正则化(Normalization)/归一化/范数化是机器学习领域提出的给予向量空间模型上的一个转换,经常被使用在分类与聚类中.

sklearn.preprocessing.normalize(x,axis=1, copy=True,  norm='l2',  return_norm='False')  

norm='l2'‘l1’,‘l2’,or ‘max’, 用于正则化的具体范数 ,l是字母
return_norm='false'是否返回所使用的范数

示例:

from sklearn.preprocessing import normalize
X1 = [[1,1,2],[2,2,4]]

#对向量进行单位化
normalize(X1, #需要求单位向量的数据
          norm='l1',
          return_norm=True #返回每个向量的范数(距离)
         )

2.2 考虑异常值的标准化方法(robust_scale()、RobustScaler())

将中位数和百分位数(默认使用四分位间距),分别代替均数和标准差用于数据标准化 。更适合于已知有离群值的数据

sklearn.preprocessing.robust_scale(
X,axis=0,with_centering=True, quantile_range(25.0,75.0),copy = True)

sklearn.preprocessing.RobustScaler(
with_centering = True, with_scaling = True, quantile_range(25.0,75.0), copy = True)

axis=0表示按列
quantile_range(25.0,75.0)用于计算离散程度的百分位数

示例:

#稳健标准化
from sklearn.preprocessing import robust_scale
from sklearn.preprocessing import RobustScaler

robust_scale(boston.data)

rs = RobustScaler()
from sklearn.datasets import load_boston
boston = load_boston()
data = rs.fit_transform(boston.data) 
print(data)

#查看data现在的一些属性
import numpy as np
np.median(data,axis = 0) #每一列的中位数
data.mean(axis = 0)  #每一列的平均值
data.std(axis = 1)  #每一行的标准差

3 数据拆分的sklearn实现

实现简单交叉验证,s折交叉验证都是在model_selection中

3.1 交叉验证的几种方式

1.简单交叉验证(分成两份)

首先随机地将已给数据分成两份,一份作为训练集,另一份作为测试集,(例如:70%数据为训练集,30%为测试集);
然后用训练集在各种条件下(例:不同的参数个数)训练模型,从而得到不同的模型; 在测试集上评价各个模型的测试误差,选出测试误差最小的模型。

  • 优点:简单方便,直接将训练集按比例拆分成训练集和验证集
  • 缺点:没有充分利用数据,结果具有偶然性。如果按1:1分,会损失50%的数据信息,因为这一部分没有用来训练模型

2.s折交叉验证 (S-fold cross validation)(分成k份):

应用最广泛,S:超参数 ,cv:交叉验证。

首先随机地将已给数据切分为S个互不相交、大小相同的子集;
然后利用S-1个子集的数据训练模型,利用余下的子集测试模型;
将这一过程对可能的S种选择重复进行;
最后选出S次评测中平均测试误差最小的模型


3.留一交叉验证 (LOOCV)

数据量很少的时候使用,还有LPOCV

S折交叉验证的特殊情形是S=N,称为留一交叉验证(leave-one-out crossvalidation),往往在数据缺乏的情况下使用。这里,N 是给定数据集的容量。


3.2 拆分为训练集与测试集

sklearn.model_selection.train_test_split(
*arrays:  等长度的需要拆分的数据对象  
test_size = 0.25,  用于验证模型的样本比例  
train_size,   用于训练模型的样本比例  
test_size, train_size  一般只设置一个,两个同时设置时和需要小于等于1  
random_state:  随机种子  
shuffle:  洗牌  
stratify = None:array-like or None,   是否按指定类别标签对数据做分层拆分 )  

shuffle 洗牌,每个类别随机排列,拆分训练集和测试集较为公平,每个类别都有

示例:

#拆分训练集与测试集
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(boston.data,boston.target,test_size=0.3)

#查看train集的长度
print(len(y_train))
print(len(X_train))

3.3 sklearn交叉验证常用命令

sklearn.model_selection. 下

  • cross_val_score() 将拆分和评价合并执行
  • cross_validate() 同时使用多个评价指标
  • cross_val_predict() 使用交叉验证后的模型进行预测

示例:

from sklearn.model_selection import cross_val_score
from sklearn.model_selection import cross_validate
from sklearn.model_selection import cross_val_predict

#以cross_val_score为例,导入线性回归模块
from sklearn.linear_model import LinearRegression  #R^2作为评价指标,在-1到1之间
reg = LinearRegression()
scores = cross_val_score(reg, boston.data, boston.target, cv=10)
print(scores)

scores.mean(),scores.std()  #评分的平均值很低,Boston数据集是有顺序排列的,所以结果不好

scores = cross_val_score(reg, boston.data, boston.target,
                         scoring = 'explained_variance', cv = 10 )
print(scores)
                     

scoring = 'explained_variance'使用解释方差(Explained Variance,简称 EV)作为评价指标,
是一种用于衡量模型预测结果与实际结果之间差异的指标.

3.4 保证案例顺序的随机性

kFold等函数有一个内置参数shuffle(默认为False),可以在拆分数据集之前将数据索引随机排序 。
但是由于cross_val_score没有此参数,因此必要时应当先对数据进行随机排序

示例:

#对数据进行随机重排,保证拆分的均匀性
import numpy as np
X, y = boston.data, boston.target
indices = np.arange(y.shape[0])
np.random.shuffle(indices)
X, y = X[indices], y[indices]

from sklearn.linear_model import LinearRegression  #线性回归模型
reg = LinearRegression()
scores = cross_val_score(reg, X, y, cv = 10)

#查看scores的一些指标
print(scores.mean(), scores.std())

3.5 sklearn.model_selection.cross_validate()

sklearn.model_selection.cross_validate(
    estimator:  用于拟合数据的估计器对象名称,  
    X:  array-like, 用于拟合模型的数据阵  
    y=None:  array-like, 有监督模型使用的因变量  
    groups = None:  array-like,形如(n_samples),样本拆分时使用的分组标签
    scoring=None:  str, callable, list/tuple, dict or None  
            模型评分的计算方法,多评估指标的时候用list/dict等方式提供  
            
    cv =  None:  设定交互验证时的样本拆分策略
        None,  使用默认的三组拆分
        integer, 设定具体的拆分组数  
        object / iterable 用于设定拆分  
    
    n_jobs = 1, verbose = 0, fit_params = None, pre_dispatch = '2*n_jobs',  
    return_train_score = True: boolean,是否返回训练集评分)
  • 返回:每轮模型对应评分的字典,shape=(n_splits, )

示例:

from sklearn.model_selection import cross_validate
scoring = ['r2', 'explained_variance']

#多种评判标准, scoring=scoring
scores = cross_validate(reg, X, y, cv = 10, scoring = scoring, return_train_score = False)
print(scores)

3.6 sklearn.model_selection.cross_val_predict()

sklearn.model_selection.cross_val_predict(
    estimator, X, y = None,  
    groups = None, cv = None,
    n_jobs = 1, verbose = 0, fit_params = None, pre_dispatch = '2*n_jobs',
    method = 'predict_proba'  时各列按照升序对应各个类别
)
  • 返回:ndarry, 模型对应的各案例的预测值

示例:

from sklearn.model_selection import cross_val_predict
pred = cross_val_predict(reg, X, y, cv = 10)
pred[:10]

# r^2评价指标
from sklearn.metrics import r2_score
r2_score(y, pred)

4 sklearn实现决策树

4.1 class sklearn.tree.DecisionTreeClassifier()

sklearn.tree.DecisionTreeClassifier(  
    criterion = 'gini':  衡量节点拆分质量的指标,{'gini', 'entropy'}  
    splitter = 'best':  节点拆分时的策略  
                'best'代表最佳拆分,'random'为最佳随机拆分  
    max_depth = None:  树生长的最大深度(高度)  
    **min_samples_split = 2:  结点允许进一步分枝时最低样本数
    **min_samples_leaf = 1:  叶节点的最低样本量 
    min_weight_fraction_leaf = 0.0:  有权重时叶节点的最低权重分值  
    max_features = 'auto': int/float/string/None,  搜索分支时考虑的特征数  
                    'auto'/'sqrt', max_features = sqrt(n_features)  
                    'log2', max_features = log2(n_features)  
                    None, max_features = n_features  
    random_state = None  
    max_leaf_nodes = None:  最高叶节点数量   
    min_impurity_decrease = 0.0:  分枝时需要的最低信息量下降量  
    class_weight = None, presort = False  
    )

DecisionTreeClassifier类的属性:
classes_: array of shape = {n_classes} or a list of such arrays
feature_importances: 特征重要性评价,总和为1,也被称为gini重要性
max_features: int
n_classes_: int or list
n_features: int
n_outputs : int
tree_: Tree object

示例:

#导入决策树分类模块
from sklearn.tree import DecisionTreeClassifier
#导入iris数据集
from sklearn.datasets import load_iris
iris = load_iris()
#决策树实例化
ct = DecisionTreeClassifier()
#模型训练
ct.fit(iris.data, iris.target)

#查看此时ct的属性
ct.max_features_
ct.feature_importances_   #数值更大的特征更重要

ct.predict(iris.data)

4.2 classification_report()

反应模型的评分

from sklearn.metrics import classification_report
print(classification_report(iris.target,ct.predict(iris.data)))

运行结果:
在这里插入图片描述

4.3 分类结果的呈现:混淆矩阵

可在该矩阵的基础上进一步计算分类别的各种指标

sklearn.metrics.confusion_matrix(y_ture,y_pred,labels=None,sample_weight=None)
  • 输出预测类别和实际类别的交叉矩阵(混淆矩阵)
  • 函数返回: array, shape={n_classes, n_classes}

示例:

from sklearn.metrics import confusion_matrix
confusion_matrix(iris.target,ct.predict(iris.data))
x_train, x_test, y_train, y_test = train_test_split(iris.data,iris.target,test_size=0.3)

# 混淆矩阵
cm = confusion_matrix(y_train, ct.predict(x_train))
print(cm)

#自定义类别顺序输出混淆矩阵
cm = confusion_matrix(y_train, ct.predict(x_train), labels = [2,1,0])
print(cm)

可以用热力图形式展现:

%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
sns.heatmap(cm, cmap = sns.color_palette("Blues"), annot = True)

4.4 sklearn.tree.export_graphviz()

sklearn.tree.export_graphviz(
    decision_tree, 
    out_file='tree.dot',
    max_depth = None, feature_names = None, class_names = None,  
    label = 'all': {'all', 'root', 'none'},
    filled = False, 
    leaves_parallel = False ,
    impurity = True, node_ids = False,  
    proportion = False,
    rotate = False,
    rounded = False,  
    special_characters = False,
    precision = 3)  

decision_tree 分类器名称
out_file='tree.dot' 文件名,后缀为’.dot’
label = 'all': {‘all’, ‘root’, ‘none’}, 是否显示杂质测量指标
filled = False: 是否对节点填色加强表示
leaves_parallel = False: 是否在树底部绘制所有叶节点
proportion = False: 是否给出节点样本占比而不是样本量
rotate = False: 是否从左至右绘图
rounded = False: 是否绘制圆角框而不是直角长方框
special_characters = False: 是否忽略ps兼容的特殊字符

示例:

from sklearn.tree import export_graphviz
export_graphviz(ct, out_file = 'tree.dot', feature_names=iris.feature_names,
               class_names = iris.target_names)




实战:尝试用二分法对iris数据进行拆分,并完成决策树模型和评估工作

#导入iris数据集
from sklearn.datasets import load_iris
iris = load_iris()
x = iris.data
y = iris.target

#拆分数据集
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.3, random_state=42,shuffle=True)

#构建决策树
from sklearn.tree import DecisionTreeClassifier
ct = DecisionTreeClassifier()
ct.fit(x_train, y_train)
y_pred = ct.predict(x_test)

#对决策树评分
from sklearn.metrics import classification_report
print(classification_report(y_test,y_pred))

#画出决策树,保存为"tree2.dot"文件
from sklearn.tree import export_graphviz
export_graphviz(ct, out_file = 'tree2.dot', feature_names=iris.feature_names, class_names = iris.target_names, filled = True,rounded = True)

这里结合了graphviz展现决策树,在gvedit中打开"tree2.dot":
在这里插入图片描述
当然也可以在jupter notebook中用graphviz展示。

以上是本篇笔记的全部内容,欢迎留言!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值