Set_output API の使用方法

Machine LearningMachine LearningBeginner
今すぐ練習

This tutorial is from open-source community. Access the source code

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、Scikit-Learn の set_output API を使って、トランスフォーマーを設定して pandas の DataFrame を出力する方法を学びます。この機能は、Scikit-Learn で異種データやパイプラインを扱う際に便利です。

VM のヒント

VM の起動が完了したら、左上隅をクリックして ノートブック タブに切り替えて、Jupyter Notebook を使って練習しましょう。

時々、Jupyter Notebook が読み込み終わるまで数秒待つ必要がある場合があります。Jupyter Notebook の制限により、操作の検証は自動化できません。

学習中に問題がある場合は、Labby にお問い合わせください。セッション後にフィードバックを提供してください。すぐに問題を解決いたします。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL sklearn(("Sklearn")) -.-> sklearn/CoreModelsandAlgorithmsGroup(["Core Models and Algorithms"]) sklearn(("Sklearn")) -.-> sklearn/ModelSelectionandEvaluationGroup(["Model Selection and Evaluation"]) sklearn(("Sklearn")) -.-> sklearn/UtilitiesandDatasetsGroup(["Utilities and Datasets"]) sklearn(("Sklearn")) -.-> sklearn/DataPreprocessingandFeatureEngineeringGroup(["Data Preprocessing and Feature Engineering"]) ml(("Machine Learning")) -.-> ml/FrameworkandSoftwareGroup(["Framework and Software"]) sklearn/CoreModelsandAlgorithmsGroup -.-> sklearn/linear_model("Linear Models") sklearn/DataPreprocessingandFeatureEngineeringGroup -.-> sklearn/preprocessing("Preprocessing and Normalization") sklearn/DataPreprocessingandFeatureEngineeringGroup -.-> sklearn/feature_selection("Feature Selection") sklearn/DataPreprocessingandFeatureEngineeringGroup -.-> sklearn/pipeline("Pipeline") sklearn/DataPreprocessingandFeatureEngineeringGroup -.-> sklearn/impute("Impute") sklearn/ModelSelectionandEvaluationGroup -.-> sklearn/model_selection("Model Selection") sklearn/ModelSelectionandEvaluationGroup -.-> sklearn/compose("Composite Estimators") sklearn/UtilitiesandDatasetsGroup -.-> sklearn/datasets("Datasets") ml/FrameworkandSoftwareGroup -.-> ml/sklearn("scikit-learn") subgraph Lab Skills sklearn/linear_model -.-> lab-49285{{"Set_output API の使用方法"}} sklearn/preprocessing -.-> lab-49285{{"Set_output API の使用方法"}} sklearn/feature_selection -.-> lab-49285{{"Set_output API の使用方法"}} sklearn/pipeline -.-> lab-49285{{"Set_output API の使用方法"}} sklearn/impute -.-> lab-49285{{"Set_output API の使用方法"}} sklearn/model_selection -.-> lab-49285{{"Set_output API の使用方法"}} sklearn/compose -.-> lab-49285{{"Set_output API の使用方法"}} sklearn/datasets -.-> lab-49285{{"Set_output API の使用方法"}} ml/sklearn -.-> lab-49285{{"Set_output API の使用方法"}} end

Iris データセットを読み込む

まず、set_output API を示すために、Iris データセットを DataFrame として読み込みます。

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

X, y = load_iris(as_frame=True, return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=0)
X_train.head()

トランスフォーマーを設定して DataFrame を出力する

preprocessing.StandardScaler などの推定器を設定して DataFrame を返すには、set_output を呼び出します。

from sklearn.preprocessing import StandardScaler

scaler = StandardScaler().set_output(transform="pandas")

scaler.fit(X_train)
X_test_scaled = scaler.transform(X_test)
X_test_scaled.head()

fit 後に transform を設定する

set_output は、fit の後に呼び出すことができ、その後に transform を設定することができます。

scaler2 = StandardScaler()

scaler2.fit(X_train)
X_test_np = scaler2.transform(X_test)
print(f"Default output type: {type(X_test_np).__name__}")

scaler2.set_output(transform="pandas")
X_test_df = scaler2.transform(X_test)
print(f"Configured pandas output type: {type(X_test_df).__name__}")

パイプラインを設定して DataFrame を出力する

pipeline.Pipeline では、set_output を使用してすべてのステップを設定して DataFrame を出力します。

from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.feature_selection import SelectPercentile

clf = make_pipeline(
    StandardScaler(), SelectPercentile(percentile=75), LogisticRegression()
)
clf.set_output(transform="pandas")
clf.fit(X_train, y_train)

タイタニック号のデータセットを読み込む

次に、compose.ColumnTransformer と異種データを使った set_output を示すために、タイタニック号のデータセットを読み込みます。

from sklearn.datasets import fetch_openml

X, y = fetch_openml(
    "titanic", version=1, as_frame=True, return_X_y=True, parser="pandas"
)
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y)

set_output をグローバルに設定する

set_output API は、set_config を使用して transform_output"pandas" に設定することでグローバルに設定できます。

from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.impute import SimpleImputer
from sklearn import set_config

set_config(transform_output="pandas")

num_pipe = make_pipeline(SimpleImputer(), StandardScaler())
num_cols = ["age", "fare"]
ct = ColumnTransformer(
    (
        ("numerical", num_pipe, num_cols),
        (
            "categorical",
            OneHotEncoder(
                sparse_output=False, drop="if_binary", handle_unknown="ignore"
            ),
            ["embarked", "sex", "pclass"],
        ),
    ),
    verbose_feature_names_out=False,
)
clf = make_pipeline(ct, SelectPercentile(percentile=50), LogisticRegression())
clf.fit(X_train, y_train)

config_context を使って set_output を設定する

config_context を使って出力タイプを設定する場合、transform または fit_transform が呼び出されたときの設定が有効になります。

scaler = StandardScaler()
scaler.fit(X_train[num_cols])

with config_context(transform_output="pandas"):
    X_test_scaled = scaler.transform(X_test[num_cols])
X_test_scaled.head()

まとめ

この実験では、Scikit-Learn の set_output API を使って、トランスフォーマーを設定して pandas DataFrame を出力する方法を学びました。推定器を設定して DataFrame を出力する方法、パイプラインを設定して DataFrame を出力する方法、および set_config を使って set_output をグローバルに設定する方法を示しました。また、config_context を使って set_output を設定する方法も学びました。