sklearn pipeline_sklearn基础
參考官方文檔:https://scikit-learn.org/stable/getting_started.html
Fitting and predicting: estimator basics(擬合和預測:估計器基礎)
Scikit-learn內置了數十種機器學習算法和模型,這些算法和模型叫做估計器。每一個估計器都可以使用其擬合方法來擬合某些數據。下面是我們使用隨機森林模型擬合一些數據的例子:
from sklearn.ensemble import RandomForestClassifierclf = RandomForestClassifier(random_state=0)
X = [[ 1, 2, 3], # 2 samples, 3 features
[11, 12, 13]]
y = [0, 1] # classes of each sample
clf.fit(X, y)
fit方法通常接收兩個參數:
樣本矩陣X。X的大小通常為(n_samples,n_features),這意味著樣本表示為行,特征表示為列。
目標值y是用于回歸任務的實數,或者是用于分類的整數(或任何其他離散值集)。對于無監督學習任務,無需指定y。y通常是1d數組,其中第i個條目對應于X的第i個樣本(行)的目標。
x,y通常希望是numpy數組格式(因為sklearn是基于numpy開發的包),或者等價類似于數組類型(pandas.DataFrame)。一些評估器也可以使用稀疏矩陣類型。一旦估計器擬合過數據了,就可以直接拿來做預測而無需重復訓練。
clf.predict([[4, 5, 6], [14, 15, 16]]) # predict classes of new data
Transformers and pre-processors(數據變換器和預處理器)
機器學習工作流通常包含許多不同部分,一個傳統的流程是包含一個數據預處理步驟(數據變換、缺失值填補等)和一個最后的預測器。
在sklearn中,不同的估計器對象有著相同的數據變換API(事實上他們都是繼承于BaseEstimator類)。變換器有transform方法(類似于predict方法)用來輸出一個尺寸相同的變換后的矩陣。
X = [[0, 15],
[1, -10]]
StandardScaler().fit(X).transform(X)
有時候你想對不同的特征使用不同的數據變換方法,你可以使用 ColumnTransformer方法。
Pipelines: chaining pre-processors and estimators(管道:鏈接預處理器和估計器)
我們可以使用管道鏈接數據變換器和預測器,管道像傳統的預測器一樣提供相同的fit和predict方法。使用管道可以使我們變得代碼簡潔易懂,并且可以避免我們犯數據泄露的錯誤。
from sklearn.preprocessing import StandardScalerfrom sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# create a pipeline object
pipe = make_pipeline(
StandardScaler(),
LogisticRegression(random_state=0)
)
# load the iris dataset and split it into train and test sets
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
# fit the whole pipeline
pipe.fit(X_train, y_train)
# we can now use it like any other estimator
accuracy_score(pipe.predict(X_test), y_test)
Model evaluation(模型評估)
訓練數據并不代表我們的模型能夠在未知數據上表現良好,所以我們需要評估模型。我們使用train_test_split方法劃分訓練集測試集,除此之外,sklearn還提供了一些其他的工具進行模型評估,特別是cross-validation(交叉驗證)。我們這里簡單演示一下使用五折交叉驗證的流程。
from sklearn.datasets import make_regressionfrom sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_validate
X, y = make_regression(n_samples=1000, random_state=0)
lr = LinearRegression()
result = cross_validate(lr, X, y) # defaults to 5-fold CV
result['test_score'] # r_squared score is high because dataset is easy
Automatic parameter searches(自動參數搜索)
所有估計器都有可以調整的參數(在文獻中通常稱為超參數)。估計器的泛化能力通常主要取決于幾個參數。例如RandomForestRegressor具有一個n_estimators參數,該參數確定林中樹木的數量,以及max_depth參數,該參數確定每棵樹的最大深度。通常,不清楚這些參數的確切值是多少,因為它們取決于手頭的數據。Scikit-learn提供了自動查找最佳參數組合的工具(通過交叉驗證)。在以下示例中,我們使用RandomizedSearchCV對象在隨機森林的參數空間中進行隨機搜索。搜索結束后,RandomizedSearchCV的表現類似于已配備最佳參數集的RandomForestRegressor。
from sklearn.datasets import fetch_california_housingfrom sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import RandomizedSearchCV
from sklearn.model_selection import train_test_split
from scipy.stats import randint
X, y = fetch_california_housing(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
# define the parameter space that will be searched over
param_distributions = {'n_estimators': randint(1, 5),
'max_depth': randint(5, 10)}
# now create a searchCV object and fit it to the data
search = RandomizedSearchCV(estimator=RandomForestRegressor(random_state=0),
n_iter=5,
param_distributions=param_distributions,
random_state=0)
search.fit(X_train, y_train)
search.best_params_
# the search object now acts like a normal random forest estimator
# with max_depth=9 and n_estimators=4
search.score(X_test, y_test)
實際上,您幾乎總是想在管道上而不是單個估計器上進行搜索。主要原因之一是,如果在不使用流水線的情況下對整個數據集應用預處理步驟,然后執行任何類型的交叉驗證,那么您將打破訓練和測試數據之間獨立性的基本假設。實際上,由于您是使用整個數據集對數據進行預處理的,因此有關訓練集的一些信息可用于訓練集。這將導致高估估計器的泛化能力。使用管道進行交叉驗證和搜索將在很大程度上避免您遇到這個常見的陷阱。
sklearn 常用方法
總結
以上是生活随笔為你收集整理的sklearn pipeline_sklearn基础的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python完整安装顺序_Python安
- 下一篇: 网页中加载obj模型比较慢_R语言估计时