.. 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-15 .. code-block:: default from sklearn import datasets iris = datasets.load_iris() X = iris.data y = iris.target .. GENERATED FROM PYTHON SOURCE LINES 16-17 Fit a PCA .. GENERATED FROM PYTHON SOURCE LINES 17-21 .. code-block:: default 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 22-23 Project the data in 2D .. GENERATED FROM PYTHON SOURCE LINES 23-25 .. code-block:: default X_pca = pca.transform(X) .. GENERATED FROM PYTHON SOURCE LINES 26-27 Visualize the data .. GENERATED FROM PYTHON SOURCE LINES 27-36 .. code-block:: default 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): 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.091 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-python :download:`Download Python source code: plot_pca.py ` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_pca.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_