.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/miscellaneous/plot_set_output.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. or to run this example in your browser via JupyterLite or Binder .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_miscellaneous_plot_set_output.py: ============================================ تقديم واجهة برمجة التطبيقات `set_output` ============================================ .. currentmodule:: sklearn هذا المثال سيوضح واجهة برمجة التطبيقات `set_output` لتكوين المحولات لإخراج إطارات بيانات باندا. يمكن تكوين `set_output` لكل مقدر عن طريق استدعاء طريقة `set_output` أو بشكل عام عن طريق تعيين `set_config(transform_output="pandas")`. للحصول على التفاصيل، راجع `SLEP018 `__. .. GENERATED FROM PYTHON SOURCE LINES 11-12 أولاً، نقوم بتحميل مجموعة بيانات إيريس كإطار بيانات لإظهار واجهة برمجة التطبيقات `set_output`. .. GENERATED FROM PYTHON SOURCE LINES 12-19 .. code-block:: Python 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() .. raw:: html
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)
60 5.0 2.0 3.5 1.0
1 4.9 3.0 1.4 0.2
8 4.4 2.9 1.4 0.2
93 5.0 2.3 3.3 1.0
106 4.9 2.5 4.5 1.7


.. GENERATED FROM PYTHON SOURCE LINES 20-22 لتكوين مقدر مثل :class:`preprocessing.StandardScaler` لإرجاع إطارات البيانات، استدع `set_output`. تتطلب هذه الميزة تثبيت باندا. .. GENERATED FROM PYTHON SOURCE LINES 22-31 .. code-block:: Python 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() .. raw:: html
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)
39 -0.894264 0.798301 -1.271411 -1.327605
12 -1.244466 -0.086944 -1.327407 -1.459074
48 -0.660797 1.462234 -1.271411 -1.327605
23 -0.894264 0.576989 -1.159419 -0.933197
81 -0.427329 -1.414810 -0.039497 -0.275851


.. GENERATED FROM PYTHON SOURCE LINES 32-33 يمكن استدعاء `set_output` بعد `fit` لتكوين `transform` بعد ذلك. .. GENERATED FROM PYTHON SOURCE LINES 33-43 .. code-block:: Python scaler2 = StandardScaler() scaler2.fit(X_train) X_test_np = scaler2.transform(X_test) print(f"نوع الإخراج الافتراضي: {type(X_test_np).__name__}") scaler2.set_output(transform="pandas") X_test_df = scaler2.transform(X_test) print(f"نوع الإخراج المُهيأ من باندا: {type(X_test_df).__name__}") .. rst-class:: sphx-glr-script-out .. code-block:: none نوع الإخراج الافتراضي: ndarray نوع الإخراج المُهيأ من باندا: DataFrame .. GENERATED FROM PYTHON SOURCE LINES 44-46 في :class:`pipeline.Pipeline`، يقوم `set_output` بتكوين جميع الخطوات لإخراج إطارات البيانات. .. GENERATED FROM PYTHON SOURCE LINES 46-56 .. code-block:: Python from sklearn.feature_selection import SelectPercentile from sklearn.linear_model import LogisticRegression from sklearn.pipeline import make_pipeline clf = make_pipeline( StandardScaler(), SelectPercentile(percentile=75), LogisticRegression() ) clf.set_output(transform="pandas") clf.fit(X_train, y_train) .. raw:: html
Pipeline(steps=[('standardscaler', StandardScaler()),
                    ('selectpercentile', SelectPercentile(percentile=75)),
                    ('logisticregression', LogisticRegression())])
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.


.. GENERATED FROM PYTHON SOURCE LINES 57-59 يتم تكوين كل محول في خط الأنابيب لإرجاع إطارات البيانات. هذا يعني أن خطوة الانحدار اللوجستي النهائي تحتوي على أسماء ميزات الإدخال. .. GENERATED FROM PYTHON SOURCE LINES 59-61 .. code-block:: Python clf[-1].feature_names_in_ .. rst-class:: sphx-glr-script-out .. code-block:: none array(['sepal length (cm)', 'petal length (cm)', 'petal width (cm)'], dtype=object) .. GENERATED FROM PYTHON SOURCE LINES 62-64 .. note:: إذا استخدم المرء طريقة `set_params`، فسيتم استبدال المحول بآخر بتنسيق الإخراج الافتراضي. .. GENERATED FROM PYTHON SOURCE LINES 64-68 .. code-block:: Python clf.set_params(standardscaler=StandardScaler()) clf.fit(X_train, y_train) clf[-1].feature_names_in_ .. rst-class:: sphx-glr-script-out .. code-block:: none array(['x0', 'x2', 'x3'], dtype=object) .. GENERATED FROM PYTHON SOURCE LINES 69-71 للحفاظ على السلوك المقصود، استخدم `set_output` على المحول الجديد مسبقاً .. GENERATED FROM PYTHON SOURCE LINES 71-76 .. code-block:: Python scaler = StandardScaler().set_output(transform="pandas") clf.set_params(standardscaler=scaler) clf.fit(X_train, y_train) clf[-1].feature_names_in_ .. rst-class:: sphx-glr-script-out .. code-block:: none array(['sepal length (cm)', 'petal length (cm)', 'petal width (cm)'], dtype=object) .. GENERATED FROM PYTHON SOURCE LINES 77-79 بعد ذلك، نقوم بتحميل مجموعة بيانات تيتانيك لإظهار `set_output` مع :class:`compose.ColumnTransformer` والبيانات غير المتجانسة. .. GENERATED FROM PYTHON SOURCE LINES 79-84 .. code-block:: Python from sklearn.datasets import fetch_openml X, y = fetch_openml("titanic", version=1, as_frame=True, return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y) .. GENERATED FROM PYTHON SOURCE LINES 85-87 يمكن تكوين واجهة برمجة التطبيقات `set_output` بشكل عام باستخدام :func:`set_config` و تعيين `transform_output` إلى `"pandas"`. .. GENERATED FROM PYTHON SOURCE LINES 87-113 .. code-block:: Python from sklearn import set_config from sklearn.compose import ColumnTransformer from sklearn.impute import SimpleImputer from sklearn.preprocessing import OneHotEncoder, StandardScaler 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) clf.score(X_test, y_test) .. rst-class:: sphx-glr-script-out .. code-block:: none 0.7804878048780488 .. GENERATED FROM PYTHON SOURCE LINES 114-116 مع التهيئة العامة، تخرج جميع المحولات إطارات بيانات. هذا يسمح لنا بسهولة رسم معاملات الانحدار اللوجستي مع أسماء الميزات المقابلة. .. GENERATED FROM PYTHON SOURCE LINES 116-122 .. code-block:: Python import pandas as pd log_reg = clf[-1] coef = pd.Series(log_reg.coef_.ravel(), index=log_reg.feature_names_in_) _ = coef.sort_values().plot.barh() .. image-sg:: /auto_examples/miscellaneous/images/sphx_glr_plot_set_output_001.png :alt: plot set output :srcset: /auto_examples/miscellaneous/images/sphx_glr_plot_set_output_001.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 123-125 من أجل توضيح وظيفة :func:`config_context` أدناه، دعنا أولاً إعادة تعيين `transform_output` إلى قيمته الافتراضية. .. GENERATED FROM PYTHON SOURCE LINES 125-127 .. code-block:: Python set_config(transform_output="default") .. GENERATED FROM PYTHON SOURCE LINES 128-131 عند تكوين نوع الإخراج باستخدام :func:`config_context` فإن التهيئة في الوقت الذي يتم فيه استدعاء `transform` أو `fit_transform` هي ما يهم. تعيين هذه فقط عند إنشاء أو تكييف المحول ليس له أي تأثير. .. GENERATED FROM PYTHON SOURCE LINES 131-136 .. code-block:: Python from sklearn import config_context scaler = StandardScaler() scaler.fit(X_train[num_cols]) .. raw:: html
StandardScaler()
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.


.. GENERATED FROM PYTHON SOURCE LINES 137-142 .. code-block:: Python with config_context(transform_output="pandas"): # سيكون إخراج التحويل إطار بيانات باندا X_test_scaled = scaler.transform(X_test[num_cols]) X_test_scaled.head() .. raw:: html
age fare
714 0.139067 0.446265
101 0.627743 -0.081671
721 0.418311 -0.519142
147 NaN 0.168547
661 -0.838285 -0.508223


.. GENERATED FROM PYTHON SOURCE LINES 143-144 خارج مدير السياق، سيكون الإخراج مصفوفة نومبي .. GENERATED FROM PYTHON SOURCE LINES 144-145 .. code-block:: Python X_test_scaled = scaler.transform(X_test[num_cols]) X_test_scaled[:5] .. rst-class:: sphx-glr-script-out .. code-block:: none array([[ 0.14, 0.45], [ 0.63, -0.08], [ 0.42, -0.52], [ nan, 0.17], [-0.84, -0.51]]) .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.191 seconds) .. _sphx_glr_download_auto_examples_miscellaneous_plot_set_output.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/scikit-learn/scikit-learn/main?urlpath=lab/tree/notebooks/auto_examples/miscellaneous/plot_set_output.ipynb :alt: Launch binder :width: 150 px .. container:: lite-badge .. image:: images/jupyterlite_badge_logo.svg :target: ../../lite/lab/index.html?path=auto_examples/miscellaneous/plot_set_output.ipynb :alt: Launch JupyterLite :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_set_output.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_set_output.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_set_output.zip ` .. include:: plot_set_output.recommendations .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_