zoukankan      html  css  js  c++  java
  • Python中使用sklearn 的 Pipeline 管道机制

    pipeline管道机制使用方法:

    流水线的输入为一连串的数据挖掘步骤,其中最后一步必须是估计器(Estimator),可理解成分类器
    前几步是转换器(Transformer)。输入的数据集经过转换器的处理后,输出的结果作为下一步的输入。

    最后,用位于流水线最后一步的估计器对数据进行分类。

    每一步都用元组( ‘名称’,步骤)来表示。现在来创建流水线。

    pipe = Pipeline([('sc',StandardScaler()),
                     ('pca',PCA(n_components=2)),
                     ('clf',LogisticRegression(random_state=666))   #设置随机种子,使测试结果复现
                     ])
    #coding=gbk
    #sklearn 中pipeline管道机制的使用
    
    '''
    流水线的功能:
    跟踪记录各步骤的操作(以方便地重现实验结果)
    对各步骤进行一个封装
    确保代码的复杂程度不至于超出掌控范围
    '''
    import pandas as pd
    from sklearn.cross_validation  import train_test_split
    from sklearn.preprocessing import LabelEncoder
    data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/'
                     'breast-cancer-wisconsin/wdbc.data', header=None)
    print(data.shape)
    x, y = data.values[:,2:],data.values[:,1]
    encoder = LabelEncoder()
    y= encoder.fit_transform(y)     #将 标签 'm', 'b' 转换成1,0
    
    x_train, x_test, y_train, y_test = train_test_split(x,y,test_size= 0.2,random_state= 666)
    
    #使用pipeline管道机制
    from sklearn.preprocessing import StandardScaler        #规范化,使各特征的均值为1,方差为0
    from sklearn.decomposition import PCA
    from sklearn.linear_model import LogisticRegression
    
    from sklearn.pipeline import Pipeline
    pipe = Pipeline([('sc',StandardScaler()),
                     ('pca',PCA(n_components=2)),
                     ('clf',LogisticRegression(random_state=666))   #设置随机种子,使测试结果复现
                     ])
    pipe.fit(x_train, y_train)
    print('Test accuracy is %.3f' % pipe.score(x_test, y_test))
    # Test accuracy is 0.921

    当我们执行 pipe.fit(X_train, y_train)时,首先由StandardScaler在训练集上执行 fit和transform方法,transformed后的数据又被传递给Pipeline对象的下一步,也即PCA()。和StandardScaler一样,PCA也是执行fit和transform方法,最终将转换后的数据传递给 LosigsticRegression。


    参考:inside_zhang 的blog

  • 相关阅读:
    UOJ #455 [UER #8]雪灾与外卖 (贪心、模拟费用流)
    Codeforces 482E ELCA (LCT)
    Codeforces 798D Mike and distribution (构造)
    AtCoder AGC017C Snuke and Spells
    HDU 6089 Rikka with Terrorist (线段树)
    HDU 6136 Death Podracing (堆)
    AtCoder AGC032D Rotation Sort (DP)
    jenkins+python+kubectl实现批量更新k8s镜像
    Linux 下载最新kubectl版本的命令:
    jenkins X 和k8s CI/CD
  • 原文地址:https://www.cnblogs.com/junge-mike/p/12761094.html
Copyright © 2011-2022 走看看