.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "packages/scikit-learn/auto_examples/plot_pca.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. .. rst-class:: sphx-glr-example-title .. _sphx_glr_packages_scikit-learn_auto_examples_plot_pca.py: =============== Demo PCA in 2D =============== .. GENERATED FROM PYTHON SOURCE LINES 9-10 Load the iris data .. GENERATED FROM PYTHON SOURCE LINES 10-16 .. code-block:: Python from sklearn import datasets iris = datasets.load_iris() X = iris.data y = iris.target .. GENERATED FROM PYTHON SOURCE LINES 17-18 Fit a PCA .. GENERATED FROM PYTHON SOURCE LINES 18-23 .. code-block:: Python from sklearn.decomposition import PCA pca = PCA(n_components=2, whiten=True) pca.fit(X) .. raw:: html
PCA(n_components=2, whiten=True)
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 24-25 Project the data in 2D .. GENERATED FROM PYTHON SOURCE LINES 25-27 .. code-block:: Python X_pca = pca.transform(X) .. GENERATED FROM PYTHON SOURCE LINES 28-29 Visualize the data .. GENERATED FROM PYTHON SOURCE LINES 29-38 .. code-block:: Python target_ids = range(len(iris.target_names)) import matplotlib.pyplot as plt plt.figure(figsize=(6, 5)) for i, c, label in zip(target_ids, "rgbcmykw", iris.target_names, strict=False): plt.scatter(X_pca[y == i, 0], X_pca[y == i, 1], c=c, label=label) plt.legend() plt.show() .. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_pca_001.png :alt: plot pca :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_pca_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.101 seconds) .. _sphx_glr_download_packages_scikit-learn_auto_examples_plot_pca.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_pca.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_pca.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_pca.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_