Python 管道化 – 完整指南

本文讨论 Python 中的管道技术。在应用机器学习中,有典型的流程。它们是标准的,因为它们解决了测试设置中的数据泄漏等问题。

该管道是一个用于编排机器学习操作的 Python scikit-learn 实用程序。

管道通过允许将一系列线性数据转换链接在一起来发挥作用,从而产生可测量的建模过程。

目标是保证管道中的所有阶段(例如训练数据集或交叉验证技术中涉及的每个阶段)仅限于可用于评估的数据。

Python 流水线数据准备和建模

数据从训练数据集泄漏到测试数据集是机器学习和数据科学中的常见陷阱。

为了防止陷入这个陷阱,您需要一个可靠的测试工具,并且具有明确的训练和测试分离。包括数据准备。

数据准备是算法获取整个训练数据集访问权限的一种简单方法。例如,在学习之前对整个训练数据集进行归一化或标准化并不是一个正确的测试,因为测试集中数据的规模会影响训练数据集。

管道确保数据准备(例如标准化)仅限于交叉验证操作的每个部分,从而最大限度地减少测试工具中的数据泄漏。

下面的示例演示了这种关键的数据准备和模型评估方法。管道中有两个步骤:

  • 确保数据统一。
  • 了解如何使用线性判别分析模型。

让我们了解如何在 python 中创建管道以及如何在其中训练数据集。

导入库

创建管道需要将大量导入包加载到系统中。请记住,您需要事先安装并配置所有这些 python 包才能在程序中使用它们。

from sklearn.linear_model import LogisticRegression
from sklearn.decomposition import PCA
from sklearn.feature_selection import SelectKBest
from pandas import read_csv
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.pipeline import FeatureUnion

数据加载

在此示例中,将从包含糖尿病患者信息的公共域获取数据。我们将使用该数据库来训练我们的管道。

下面的代码演示了如何加载公共域记录:

url_data = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv"
varnames = ['var_preg', 'var_plas', 'var_pres', 'var_skin', 'var_test', 'var_mass', 'var_pedi', 'var_age', 'var_class']
vardataframe = read_csv(url_data, names=varnames)
vararray = vardataframe.values
varX = vararray[:,0:8]
varY = vararray[:,8]

在 Python 中创建管道

urlfeatures = []
urlfeatures.append(('pca', PCA(n_components=3)))
urlfeatures.append(('select_best', SelectKBest(k=6)))
feature_union = FeatureUnion(urlfeatures)
# Here, pipeline is created
estimators = []
estimators.append(('feature_union', feature_union))
estimators.append(('logistic', LogisticRegression()))
model = Pipeline(estimators)
# The pipelie is tested here
seed = 7
varkfold = KFold(n_splits=10)
dataresults = cross_val_score(model, varX, varY, cv=varkfold)
print(dataresults.mean())

Python 流水线的完整实现

整个工作流程如下所示:

# Create a pipeline that extracts features from the data then creates a model
from sklearn.linear_model import LogisticRegression
from sklearn.decomposition import PCA
from sklearn.feature_selection import SelectKBest
from pandas import read_csv
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.pipeline import FeatureUnion
 
# data laoded into global variables
url_data = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv"
varnames = ['var_preg', 'var_plas', 'var_pres', 'var_skin', 'var_test', 'var_mass', 'var_pedi', 'var_age', 'var_class']
vardataframe = read_csv(url_data, names=varnames)
vararray = vardataframe.values
varX = vararray[:,0:8]
varY = vararray[:,8]
 
# creating feature union
urlfeatures = []
urlfeatures.append(('pca', PCA(n_components=3)))
urlfeatures.append(('select_best', SelectKBest(k=6)))
feature_union = FeatureUnion(urlfeatures)
 
# Here, pipeline is created
estimators = []
estimators.append(('feature_union', feature_union))
estimators.append(('logistic', LogisticRegression()))
model = Pipeline(estimators)
 
# The pipelie is tested here
seed = 7
varkfold = KFold(n_splits=10)
dataresults = cross_val_score(model, varX, varY, cv=varkfold)
print(dataresults.mean())

输出

通过管道完成平均计算

让我们看另一个例子,以更好地理解管道测试。

在下面的代码中,将iris 数据库加载到测试管道中。Iris 数据库是 sklearn 提供的用于测试管道的数据库分类。在此示例中,通过将单个数据库分成相等的两半,使用单个数据库来训练和测试管道,即 50% 的数据将加载到测试管道中,而其余一半将用于训练管道。

from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.tree import DecisionTreeClassifier
# database is imported from inbuilt sklearn datasets
iris = datasets.load_iris()
X = iris.data
y = iris.target
 
#The data spliting is executed here
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.50)
# importing pipes for making the Pipe flow
from sklearn.pipeline import Pipeline
# The sequence of pipe flow is :
# PCA dimension is reduced by 2 >> Data gets scaled >> Classification of decission tree
pipe = Pipeline([('pca', PCA(n_components = 2)), ('std', StandardScaler()), ('decision_tree', DecisionTreeClassifier())], verbose = True)
 
# fitting the data in the pipeline
pipe.fit(X_train, y_train)
 
# scoring data
from sklearn.metrics import accuracy_score
print(accuracy_score(y_test, pipe.predict(X_test)))

输出

管道流量输出

结论

在本文中,我们了解了管道以及如何测试和训练它。我们还了解了 sklearn 导入包以及它的数据库和函数如何帮助创建数据测试管道。我们进一步了解了如何使用公共域记录来训练管道,并且我们还观察了如何拆分 sklearn 的内置数据库以提供测试和训练数据。