.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/ensemble/plot_feature_transformation.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_ensemble_plot_feature_transformation.py: =============================================== تحويل الميزات باستخدام مجموعات الأشجار =============================================== قم بتحويل ميزاتك إلى مساحة متفرقة ذات أبعاد أعلى. ثم قم بتدريب نموذج خطي على هذه الميزات. قم بتدريب مجموعة من الأشجار (أشجار عشوائية تمامًا، أو غابة عشوائية، أو أشجار معززة بالتدرج) على مجموعة التدريب. بعد ذلك، يتم تعيين فهرس ميزة عشوائي ثابت لكل ورقة من كل شجرة في المجموعة في مساحة ميزات جديدة. يتم بعد ذلك ترميز هذه المؤشرات الورقية بطريقة "واحد مقابل الكل". يمر كل عينة عبر قرارات كل شجرة في المجموعة وتنتهي في ورقة واحدة لكل شجرة. يتم ترميز العينة عن طريق تعيين قيم الميزات لهذه الأوراق إلى 1 وقيم الميزات الأخرى إلى 0. بعد ذلك، يكون المحول الناتج قد تعلم تضمينًا فئويًا إشرافيًا، متفرقًا، عالي الأبعاد للبيانات. .. GENERATED FROM PYTHON SOURCE LINES 14-17 .. code-block:: Python # المؤلفون: مطوري scikit-learn # معرف الترخيص: BSD-3-Clause .. GENERATED FROM PYTHON SOURCE LINES 18-25 أولاً، سنقوم بإنشاء مجموعة بيانات كبيرة وتقسيمها إلى ثلاث مجموعات: - مجموعة لتدريب طرق المجموعة والتي ستستخدم لاحقًا كمحول هندسة ميزات؛ - مجموعة لتدريب النموذج الخطي؛ - مجموعة لاختبار النموذج الخطي. من المهم تقسيم البيانات بهذه الطريقة لتجنب الإفراط في الملاءمة عن طريق تسريب البيانات. .. GENERATED FROM PYTHON SOURCE LINES 25-40 .. code-block:: Python import matplotlib.pyplot as plt from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split X, y = make_classification(n_samples=80_000, random_state=10) X_full_train, X_test, y_full_train, y_test = train_test_split( X, y, test_size=0.5, random_state=10 ) X_train_ensemble, X_train_linear, y_train_ensemble, y_train_linear = train_test_split( X_full_train, y_full_train, test_size=0.5, random_state=10 ) .. GENERATED FROM PYTHON SOURCE LINES 41-42 بالنسبة لكل من طرق المجموعة، سنستخدم 10 مقدرات وعمقًا أقصى يبلغ 3 مستويات. .. GENERATED FROM PYTHON SOURCE LINES 42-46 .. code-block:: Python n_estimators = 10 max_depth = 3 .. GENERATED FROM PYTHON SOURCE LINES 47-49 أولاً، سنبدأ بتدريب الغابة العشوائية والتعزيز التدرجي على مجموعة التدريب المنفصلة .. GENERATED FROM PYTHON SOURCE LINES 49-61 .. code-block:: Python random_forest = RandomForestClassifier( n_estimators=n_estimators, max_depth=max_depth, random_state=10 ) random_forest.fit(X_train_ensemble, y_train_ensemble) gradient_boosting = GradientBoostingClassifier( n_estimators=n_estimators, max_depth=max_depth, random_state=10 ) _ = gradient_boosting.fit(X_train_ensemble, y_train_ensemble) .. GENERATED FROM PYTHON SOURCE LINES 62-68 لاحظ أن :class:`~sklearn.ensemble.HistGradientBoostingClassifier` أسرع بكثير من :class:`~sklearn.ensemble.GradientBoostingClassifier` بدءًا من مجموعات البيانات المتوسطة (`n_samples >= 10_000`)، والتي لا تنطبق على المثال الحالي. :class:`~sklearn.ensemble.RandomTreesEmbedding` هي طريقة غير مشرفة وبالتالي لا تحتاج إلى التدريب بشكل مستقل. .. GENERATED FROM PYTHON SOURCE LINES 68-75 .. code-block:: Python from sklearn.ensemble import RandomTreesEmbedding random_tree_embedding = RandomTreesEmbedding( n_estimators=n_estimators, max_depth=max_depth, random_state=0 ) .. GENERATED FROM PYTHON SOURCE LINES 76-80 الآن، سنقوم بإنشاء ثلاث خطوط أنابيب ستستخدم التضمين أعلاه كـ مرحلة ما قبل المعالجة. يمكن أن يتم تضمين الأشجار العشوائية مباشرة مع الانحدار اللوجستي لأنه محول قياسي في scikit-learn. .. GENERATED FROM PYTHON SOURCE LINES 80-88 .. code-block:: Python from sklearn.linear_model import LogisticRegression from sklearn.pipeline import make_pipeline rt_model = make_pipeline(random_tree_embedding, LogisticRegression(max_iter=1000)) rt_model.fit(X_train_linear, y_train_linear) .. raw:: html
Pipeline(steps=[('randomtreesembedding',
                     RandomTreesEmbedding(max_depth=3, n_estimators=10,
                                          random_state=0)),
                    ('logisticregression', LogisticRegression(max_iter=1000))])
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 89-92 بعد ذلك، يمكننا أن ندمج الغابة العشوائية أو التعزيز التدرجي مع الانحدار اللوجستي. ومع ذلك، سيحدث تحويل الميزة عن طريق استدعاء الطريقة `apply`. يتوقع خط الأنابيب في scikit-learn استدعاء لـ `transform`. لذلك، قمنا بتغليف استدعاء `apply` داخل `FunctionTransformer`. .. GENERATED FROM PYTHON SOURCE LINES 92-119 .. code-block:: Python from sklearn.preprocessing import FunctionTransformer, OneHotEncoder def rf_apply(X, model): return model.apply(X) rf_leaves_yielder = FunctionTransformer( rf_apply, kw_args={"model": random_forest}) def rf_apply(X, model): return model.apply(X) rf_leaves_yielder = FunctionTransformer( rf_apply, kw_args={"model": random_forest}) rf_model = make_pipeline( rf_leaves_yielder, OneHotEncoder(handle_unknown="ignore"), LogisticRegression(max_iter=1000), ) rf_model.fit(X_train_linear, y_train_linear) .. raw:: html
Pipeline(steps=[('functiontransformer',
                     FunctionTransformer(func=<function rf_apply at 0x7f09b92e83a0>,
                                         kw_args={'model': RandomForestClassifier(max_depth=3,
                                                                                  n_estimators=10,
                                                                                  random_state=10)})),
                    ('onehotencoder', OneHotEncoder(handle_unknown='ignore')),
                    ('logisticregression', LogisticRegression(max_iter=1000))])
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 120-135 .. code-block:: Python def gbdt_apply(X, model): return model.apply(X)[:, :, 0] gbdt_leaves_yielder = FunctionTransformer( gbdt_apply, kw_args={"model": gradient_boosting} ) gbdt_model = make_pipeline( gbdt_leaves_yielder, OneHotEncoder(handle_unknown="ignore"), LogisticRegression(max_iter=1000), ) gbdt_model.fit(X_train_linear, y_train_linear) .. raw:: html
Pipeline(steps=[('functiontransformer',
                     FunctionTransformer(func=<function gbdt_apply at 0x7f09b92e8670>,
                                         kw_args={'model': GradientBoostingClassifier(n_estimators=10,
                                                                                      random_state=10)})),
                    ('onehotencoder', OneHotEncoder(handle_unknown='ignore')),
                    ('logisticregression', LogisticRegression(max_iter=1000))])
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 136-137 يمكننا أخيرًا عرض منحنيات ROC المختلفة لجميع النماذج. .. GENERATED FROM PYTHON SOURCE LINES 137-158 .. code-block:: Python from sklearn.metrics import RocCurveDisplay _, ax = plt.subplots() models = [ ("RT embedding -> LR", rt_model), ("RF", random_forest), ("RF embedding -> LR", rf_model), ("GBDT", gradient_boosting), ("GBDT embedding -> LR", gbdt_model), ] model_displays = {} for name, pipeline in models: model_displays[name] = RocCurveDisplay.from_estimator( pipeline, X_test, y_test, ax=ax, name=name ) _ = ax.set_title("ROC curve") .. image-sg:: /auto_examples/ensemble/images/sphx_glr_plot_feature_transformation_001.png :alt: ROC curve :srcset: /auto_examples/ensemble/images/sphx_glr_plot_feature_transformation_001.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 159-166 .. code-block:: Python _, ax = plt.subplots() for name, pipeline in models: model_displays[name].plot(ax=ax) ax.set_xlim(0, 0.2) ax.set_ylim(0.8, 1) _ = ax.set_title("ROC curve (zoomed in at top left)") .. image-sg:: /auto_examples/ensemble/images/sphx_glr_plot_feature_transformation_002.png :alt: ROC curve (zoomed in at top left) :srcset: /auto_examples/ensemble/images/sphx_glr_plot_feature_transformation_002.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 2.852 seconds) .. _sphx_glr_download_auto_examples_ensemble_plot_feature_transformation.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/ensemble/plot_feature_transformation.ipynb :alt: Launch binder :width: 150 px .. container:: lite-badge .. image:: images/jupyterlite_badge_logo.svg :target: ../../lite/lab/index.html?path=auto_examples/ensemble/plot_feature_transformation.ipynb :alt: Launch JupyterLite :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_feature_transformation.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_feature_transformation.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_feature_transformation.zip ` .. include:: plot_feature_transformation.recommendations .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_