SKlearn之情节分类概率(Plot classification probability)

这个范例的主要目的

  • 使用iris鸢尾花资料集

  • 测试不同分类器对于涵盖特定范围之资料集,分类为那一种鸢尾花的机率

  • 例如:sepal length为4cm而sepal width为3cm时被分类为versicolor的机率

 

(一)资料汇入及描述

  • 首先先汇入iris鸢尾花资料集,使用将资料存入iris = datasets.load_iris()

  • 准备X(特征资料)以及y(目标资料),仅使用两个特征方便视觉呈现

  • shape[0]为返回第一维长度,shape[1]为范围第二维长度。如果一个array是4*2的,则shape[0]=4,shape[1]=2。

print(__doc__)
import matplotlib.pyplot as plt
import numpy as np

from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from sklearn import datasets

iris = datasets.load_iris()
X = iris.data[:, 0:2]  #只使用前两个特征,方便视觉化呈现
y = iris.target

n_features = X.shape[1]

  • iris为一个dict型别资料,我们可以用以下指令来看一下资料的内容。
for key,value in iris.items() :
    try:
        print (key,value.shape)
    except:
        print (key)

#输出: 
data (150, 4)   #有150个数据,共四种特征
target (150,)   #这150个数据各是哪一种鸢尾花
target_names (3,)  #共有三种鸢尾花 setosa, versicolor, virgin
DESCR   #文件之描述
feature_names  #四个特征代表的意义
filename  #文件名

#item()的用法:
#字典 items() 方法以列表返回可遍历的(键, 值) 元组数组
#例子:
dict = {'Name': 'Runoob', 'Age': 7}
for i,j in dict.items():
    print(i, ":\t", j)

#输出:
Name :   Runoob
Age :    7

这个范例选择了四种分类器,存入一个dict资料中,分别为:

  1. L1 logistic     
  2. L2 logistic (OvR)   
  3. Linear SVC
  4. L2 logistic (Multinomial)

其中LogisticRegression 并不适合拿来做多目标的分类器,我们可以用结果图的分类机率来观察。

 

C = 10
kernel = 1.0 * RBF([1.0, 1.0])  # for GPC

# Create different classifiers.
classifiers = {
    'L1 logistic': LogisticRegression(C=C, penalty='l1',
                                      solver='saga',
                                      multi_class='multinomial',
                                      max_iter=10000),
    'L2 logistic (Multinomial)': LogisticRegression(C=C, penalty='l2',
                                                    solver='saga',
                                                    multi_class='multinomial',
                                                    max_iter=10000),
    'L2 logistic (OvR)': LogisticRegression(C=C, penalty='l2',
                                            solver='saga',
                                            multi_class='ovr',
                                            max_iter=10000),
    'Linear SVC': SVC(kernel='linear', C=C, probability=True,
                      random_state=0),
    'GPC': GaussianProcessClassifier(kernel)
}

class sklearn.linear_model.LogisticRegression(penalty=’l2’dual=Falsetol=0.0001C=1.0fit_intercept=Trueintercept_scaling=1class_weight=Nonerandom_state=Nonesolver=’warn’max_iter=100multi_class=’warn’verbose=0warm_start=Falsen_jobs=Nonel1_ratio=None)

  • : 浮点型,可选(默认= 1.0)

    正则强度的倒数;必须为正浮点数。像在支持向量机中一样,较小的值指定更强的正则化。

  • penalty : str,'l1','l2','elasticnet'或'none',可选(默认='l2')

    用于指定惩罚中使用的规范。'newton-cg','sag'和'lbfgs'求解器仅支持l2罚分。仅“ saga”求解器支持“ elasticnet”。如果为“ none”(liblinear求解器不支持),则不应用任何正则化。

  • 求解器 : str,{'newton-cg','lbfgs','liblinear','sag','saga'},可选(默认='liblinear')。

     用于优化问题的算法。

    对于小型数据集,“ liblinear”是一个不错的选择,而对于大型数据集,“ sag”和“ saga”则更快

    对于多类问题,只有'newton-cg','sag','saga'和'lbfgs'处理多项式损失。“ liblinear”仅限于“一站式”计划。

    'newton-cg','lbfgs','sag'和'saga'处理L2或不罚分

    'liblinear'和'saga'也可以处理L1罚款

    “ saga”还支持“ elasticnet”惩罚

    'liblinear'不处理任何罚款

  • multi_class : str,{'ovr','multinomial','auto'},可选(默认='ovr')

    如果选择的选项是“ ovr”,则每个标签都适合二进制问题。对于“多项式”,即使数据是二进制的,最小化损失也就是整个概率分布中的多项式损失拟合。当solver ='liblinear'时,'multinomial'不可用。如果数据是二进制的,或者如果Solver ='liblinear',则'auto'选择'ovr',否则选择'multinomial'。因为对于文本类型的数据,一般服从的都是多项式分布,不服从其他的分布.

  • max_iter : int,可选(默认= 100)

    求解程序收敛所需的最大迭代次数。

class sklearn.svm.SVC(C=1.0kernel=’rbf’degree=3gamma=’auto_deprecated’coef0=0.0shrinking=Trueprobability=Falsetol=0.001cache_size=200class_weight=Noneverbose=Falsemax_iter=-1decision_function_shape=’ovr’random_state=None)

C-Support Vector Classification.

该实现基于libsvm。拟合时间至少与样本数量成平方比例,超过成千上万的样本可能不切实际。对于大型数据集,请考虑在 sklearn.kernel_approximation.Nystroem压缩转换之后使用sklearn.linear_model.LinearSVC或 sklearn.linear_model.SGDClassifier代替。

  • : 浮点型,可选(默认= 1.0)

    误差项的惩罚参数C。

  • kernel : 字符串,可选(默认='rbf')

    指定算法中要使用的内核类型。它必须是“linear”,“poly”,“ rbf”,“ Sigmoid”,“precomputed”或a callable。如果没有给出,将使用“ rbf”。如果给出了可调用对象,则将其用于从数据矩阵中预先计算内核矩阵;那个矩阵应该是一个(n_samples, n_samples)形状的数组。

  • probability : 布尔值,可选(默认= False)

    是否启用概率估计。必须在调用之前启用此功能fit,这会使该方法变慢。

  • random_state : int,RandomState实例None,可选(默认=None)

    伪随机数生成器的种子,在对数据进行混洗以进行概率估计时使用。如果为int,则random_state是随机数生成器使用的种子(seed );否则为false。如果是RandomState实例,则random_state是随机数生成器;如果为None,则随机数生成器是所使用的RandomState实例np.random

class sklearn.gaussian_process.GaussianProcessClassifierkernel = Noneoptimizer ='fmin_l_bfgs_b'n_restarts_optimizer = 0max_iter_predict = 100warm_start = Falsecopy_X_train = Truerandom_state = Nonemulti_class ='one_vs_rest'n_jobs = None 

  • kernel : 内核对象

    指定GP协方差函数的内核。如果未通过,则默认使用内核“ 1.0 * RBF(1.0)”。请注意,内核的超参数在拟合过程中已优化。

plt.figure(figsize=(3 * 2, n_classifiers * 2))
plt.subplots_adjust(bottom=.2, top=.95)

xx = np.linspace(3, 9, 100)
yy = np.linspace(1, 5, 100).T
xx, yy = np.meshgrid(xx, yy)
Xfull = np.c_[xx.ravel(), yy.ravel()]

for index, (name, classifier) in enumerate(classifiers.items()):
    classifier.fit(X, y)

    y_pred = classifier.predict(X)
    accuracy = accuracy_score(y, y_pred)
    print("Accuracy (train) for %s: %0.1f%% " % (name, accuracy * 100))

    # View probabilities:
    probas = classifier.predict_proba(Xfull)
    n_classes = np.unique(y_pred).size
    for k in range(n_classes):
        plt.subplot(n_classifiers, n_classes, index * n_classes + k + 1)
        plt.title("Class %d" % k)
        if k == 0:
            plt.ylabel(name)
        imshow_handle = plt.imshow(probas[:, k].reshape((100, 100)),
                                   extent=(3, 9, 1, 5), origin='lower')
        plt.xticks(())
        plt.yticks(())
        idx = (y_pred == k)
        if idx.any():
            plt.scatter(X[idx, 0], X[idx, 1], marker='o', c='w', edgecolor='k')

ax = plt.axes([0.15, 0.04, 0.7, 0.05])
plt.title("Probability")
plt.colorbar(imshow_handle, cax=ax, orientation='horizontal')

plt.show()
  • plt.figure(figsize=(3 * 2, n_classifiers * 2))   

用法:matplotlib.pyplot.figure函数使用总结

  • plt.subplots_adjust(bottom=.2, top=.95)

用法:matplotlib中pyplot.subplots_adjust参数含义的理解

  • xx = np.linspace(3, 9, 100)

用法:numpy.linspace使用详解

  • xx, yy = np.meshgrid(xx, yy)

numpy.meshgrid()理解

  • numpy.c_(a,b)

numpy中np.c_和np.r_

#np.r_是按列连接两个矩阵,就是把两矩阵上下相加,要求列数相等,类似于pandas中的concat()。
#np.c_是按行连接两个矩阵,就是把两矩阵左右相加,要求行数相等,类似于pandas中的merge()。

#在numpy中,一个列表虽然是横着表示的,但它是列向量。
#现在换成2x3的向量

import numpy as np
a = np.array([[1, 2, 3],[4,5,6]])
b = np.array([[0, 0, 0],[1,1,1]])
print("-------------------a------------------")
print(a)
print("-------------------b------------------")
print(b)
print("-------------------np.r_[a,b]--------------------")
print(np.r_[a,b])
print("--------------------np.c_[a,b]-------------------")
print(np.c_[a,b])

输出如下:
-------------------a------------------
[[1 2 3]
[4 5 6]]
-------------------b------------------
[[0 0 0]
[1 1 1]]
-------------------np.r_[a,b]--------------------
[[1 2 3]
[4 5 6]
[0 0 0]
[1 1 1]]
--------------------np.c_[a,b]-------------------
[[1 2 3 0 0 0]
[4 5 6 1 1 1]]
  • xx.ravel()

功能:降维

>>> x = np.array([[1, 2, 3], [4, 5, 6]])
>>> np.ravel(x)
array([1, 2, 3, 4, 5, 6])
  • probas = classifier.predict_proba(Xfull)

sklearn中predict_proba用法(注意和predict的区别)

 

 

 

 

 

 

 

 

 

 

 

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值