{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Riccardo Andreoni",
  "title_listed": "Dimensionality Reduction Made Simple: PCA Theory and Scikit-Learn Implementation",
  "keywords": "",
  "domain": "机器学习",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/dimensionality-reduction-made-simple-pca-theory-and-scikit-learn-implementation-9d07a388df9e/",
  "publish_date": "2024-02-07",
  "corpus_stage": "",
  "notes": "",
  "id": "c4a4316a40c1",
  "collected_at": "2026-10-02T03:03:47",
  "title": "Dimensionality Reduction Made Simple: PCA Theory and Scikit-Learn Implementation | Towards Data Science",
  "body_markdown": "![Revisit consent button](../images/body-df29beacd7496220cc94.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Data Science](https://towardsdatascience.com/category/data-science/)\n# Dimensionality Reduction Made Simple: PCA Theory and Scikit-Learn Implementation\nTame the Curse of Dimensionality! Learn Dimensionality Reduction (PCA) and implement it with Python and Scikit-Learn.\n[Riccardo Andreoni](https://towardsdatascience.com/author/riccardo.andreoni/)\nFebruary 7, 202411 min read\n![Image source: unsplash.com.](../images/000.jpeg)\nImage source: [unsplash.com](https://unsplash.com/photos/3DkouQeZjp4).\nIn the novel [Flatland](https://en.wikipedia.org/wiki/Flatland), characters living in a two-dimensional world find themselves perplexed and unable to comprehend when they encounter a three-dimensional being. I use this analogy to illustrate how similar phenomena occur in Machine Learning when dealing with problems involving thousands or even millions of dimensions (i.e. features): **surprising phenomena happen** , which have **disastrous implications** on our Machine Learning models.\nI'm sure you felt stunned, at least once, by the **huge number of features** involved in modern Machine Learning problems. Every Data Science practitioner, sooner or later, will face this challenge. This article will explore the theoretical foundations and the Python implementation of the most used Dimensionality Reduction algorithm: [**Principal Component Analysis**](https://en.wikipedia.org/wiki/Principal_component_analysis#:~:text=Principal%20component%20analysis%20\\(PCA\\)%20is,the%20visualization%20of%20multidimensional%20data.) (PCA).\n> Why do we need to reduce the number of features?\nDatasets involving thousands or even millions of features are common nowadays. Adding new features to a dataset can bring in valuable information, however, they will **slow the training process** and make it **harder to find good patterns and solutions**. In Data Science this is called the **Curse of Dimensionality** and it often **** leads to skewed interpretation of data and inaccurate predictions.\nLearn this step by step with the interactive [AI and Data Scientist](https://roadmap.sh/ai-data-scientist) and [Machine Learning](https://roadmap.sh/machine-learning) roadmaps.\nMachine learning practitioners like us can benefit from the fact that for most ML problems, **the number of features can be reduced consistently**. For example, consider a picture: the pixels near the border often don't carry any valuable information. However, the techniques to safely reduce the number of features in a ML problem are not trivial and need an explanation that I will provide in this post.\n![Image by the author.](../images/001.png)\nImage by the author.\nThe tools I will present not only simplify the computation effort and boost the prediction accuracy, but they will also serve as a tool to graphically visualize high-dimensional data. For this reason, they are essential to communicate your insights with other people.\nFortunately for us, the above-mentioned technique, named Dimensionality Reduction, exists and can easily take part in every data scientist's toolbox. Moreover, Dimensionality Reduction can be easily implemented in **Python** programming thanks to the [**Scikit-Learn**](https://scikit-learn.org/) (sklearn) library.\n## Curse of Dimensionality\nThe **Curse of Dimensionality** represents **one of the biggest challenges** in Data Science as it makes algorithms **computationally intensive**. But what is it exactly?\nWhen the number of dimensions in a dataset grows substantially, the available data points become sparser and sparser, leading to an intricate cascade of computational challenges. As humans, we struggle to conceptualize more than 3, or sometimes 2, dimensions. This limitation leads to very unexpected behavior of data in high-dimensional spaces.\nFor example, consider a 2D 1x1 square. If we pick a random point inside of it, there is only a small probability for it to be located very close to a border. Numerically, there is a 0.4% probability for it to be located within a 0.001 distance from a border. Instead, in a higher-dimensional unit hypercube, as the number of edges grow, the probability for a random point to be located close to a border grows exponentially. In a 10.000-dimensional hypercube, the same probability increases to over 99.99999%. This means that in a high-dimensional space, it's very **likely to be near a border**.\nThe following experiment is even **more surprising** (or disturbing in my opinion). Take the usual 2-dimensional unit square. The distance of 2 randomly chosen points inside the square is, on average, equal to 0.52. Would you believe me if I tell you that doing the same experiment with a 100.000-dimensional unit hypercube results in an average distance of 129.09? I can prove that to you with the following Montecarlo simulation.\npython\n\n```\nimport numpy as np\ntest_dimensions = [2, 100000]\nprint('Average distance between 2 points in a unit hypercube')\nfor n_dim in test_dimensions:\n    distances = []\n    for i in range(100000):\n        rand_point_1 = np.random.uniform(size=n_dim)\n        rand_point_2 = np.random.uniform(size=n_dim)\n        dist = np.linalg.norm(rand_point_1-rand_point_2)\n        distances.append(dist)\n    avg_distance = np.mean(distances)\n    print('{} dimensions: {}'.format(n_dim, avg_distance))\n```\n\n![](../images/body-f15c97d31654cd8145c0.png)\nThe concept is even better represented by this visualization:\n![Image by the author.](../images/002.png)\nImage by the author.\nLeaving aside these funny simulations, we can extrapolate a major implication for Data Science practitioners: **there is plenty of space in high-dimensions**.\nThe consequence is that high-dimensional datasets are, with any probability, **very sparse** , and the training instances are far apart from each other. With such training data, the risk of **overfitting** your Machine Learning model is high.\nWhile, in theory, we could **add new training examples** , in practice this is not enough to cope with the increase of features. In fact, in order to maintain a constant density, the required number of training points needs to grow exponentially as a function of the number of features.\nJust to provide an example, to maintain a distance of 0.1 between each training point in a dataset with 100 features, we would need a number of training point greater than the number of atoms in the universe.\n![Image source: pixabay.com.](../images/003.jpeg)\nImage source: [pixabay.com](https://pixabay.com/illustrations/universe-sky-stars-space-cosmos-2742113/).\nThe only feasible approach is to **reduce the number of features** , and I will provide different techniques to do that while avoiding losing too much information.\n## Principal Component Analysis (PCA)\n[**Principal Component Analysis**](https://en.wikipedia.org/wiki/Principal_component_analysis#:~:text=Principal%20component%20analysis%20\\(PCA\\)%20is,the%20visualization%20of%20multidimensional%20data.) (**PCA**) is perhaps the most popular algorithm for Dimensionality Reduction. At its functioning core, it **projects the data onto a hyperplane** , aiming to make the rotated features statistically uncorrelated. The rotation is typically followed by selecting a subset of these new projected features, based on their importance in describing the data.\nAs PCA is based on projections, it is fundamental to know what this operation is. The following section explains the **Projection operation**.\n### Projection\nIn practical scenarios, a vast portion of the training instances lies close to a **lower-dimensional subspace** of the original training set hyperspace. The reasons are:\n  * **Correlation between features** : many features are heavily correlated.\n  * **Constant values** : many features assume near-to-constant values.\n\n\nTo illustrate this concept, take the following 2D dataset:\n![Image by the author](../images/004.png)\nImage by the author\nGiven the strong correlation of feature _x _1_ with feature _x _2_ , we can project the dataset on a lower-dimensional plane, which, in this case, is a line. Considering the directions identified by the black arrows, called components, if we rotate the dataset such that component 1 (_p _1_) is horizontal, we obtain:\n![Image by the author.](../images/005.png)\nImage by the author.\nAs the component _p _2_ doesn't add much information, we can project data only on component _p _1_.\n![Image by the author.](../images/006.png)\nImage by the author.\nThis is, in essence, what projection does. Its effect is even clearer considering instead a 3D dataset.\n![Image by the author.](../images/007.png)\nImage by the author.\nWe can project the original data onto a 2-dimensional plane, creating 2 new features _p _1_ , _p _2_ :\n![Image by the author.](../images/008.png)\nImage by the author.\nAs there is **no free meal in Machine Learning** , projection is not always suited for every type of dataset. If the data, in the original feature space, belong to a plane that **turns or twists** , no projection operation can preserve the original information in a lower-dimensional space.\nConsider for example the Swiss Roll dataset:\n![Image by the author.](../images/009.png)\nImage by the author.\nIt consists of a 2D plane rolled over itself. In this case, we can't effectively project the data on a plane without losing a considerable portion of the original information.\nTo avoid this amount of information loss, we will see a different method later, which aims at \"unrolling\" the data.\n### Principal Components\nAs I anticipated, PCA consists of **projecting the data onto a lower-dimensional hyperplane**. In order to preserve as much information as possible, PCA doesn't project the data on any random hyperplane. Instead, PCA selects the hyperplane on which data projection has the **maximum variance**.\n![Image by the author.](../images/010.png)\nImage by the author.\nIt is easy to understand why if we consider again a 2D example.\nPCA then considers all the axes orthogonal to the one of maximum variance and selects, between them, the one with the **remaining larger variance**.\nThis process iterates as many times as the number of dimensions in the original dataset. Each identified axis is called **Principal Component** of the dataset.\nThe question now is how to mathematically compute the Principal Components. Fortunately, linear algebra provides us with the [**Singular Value Decomposition**](https://en.wikipedia.org/wiki/Singular_value_decomposition) technique, through which we can decompose the original training set _X_ into the matrix multiplication of 3 new matrices:\n![](../images/body-43cfa91f0ff80bc44237.png)\nThe columns of the V matrix contain the direction of all the Principal Components previously identified.\n![](../images/body-f4e6f383490e610b5096.png)\nWhile it is easy to implement SVD with the [Numpy](https://numpy.org/) Python library, it is even more effortless to implement PCA with the [Scikit-learn](https://scikit-learn.org/) (sklearn) module.\nIn Scikit-learn (sklearn) I first need to create a `PCA()` object, and later fit it on the data and transform them:\npython\n\n```\nfrom sklearn.decomposition import PCA\nfrom sklearn.datasets import make_swiss_roll\n\n# Create synthetic data\nX, t = make_swiss_roll(n_samples=1000, noise=0.2, random_state=42)\n\n# Instantiate a PCA object\npca = PCA(n_components=1)\n\n# Fit the PCA object on the data\npca.fit(X)\n\n# Transform the data\nX_transformed = pca.transform(X)\n\nprint('Original data shape: ', X.shape)\nprint('Transformed data shape: ', X_transformed.shape)\n```\n\n![](../images/body-04e0bde576ad451eac48.png)\nAs we can see from the output, we reduced the original dataset dimension from 3 down to 1 dimension. This happened because we specified `n_components=1` while instantiating the `PCA()` object.\nUnless we are performing Dimensionality Reduction for **data visualization** , we might not know which is the best number of dimensions of the transformed training set.\n**Selecting the right number of dimensions** to reduce the training set down to is a big deal in Dimensionality Reduction. If the original feature space is narrow, we might try a manual iterative approach, However, in most real-world cases, the feature space is huge and we need a more robust and automized approach.\nIn order to introduce said approach, I first need to define the **Explained Variance Ratio** (EVR). In simple terms, the EVR is defined as the percentage of the variance of the original dataset which lies along each Principal Component.\nAs Scikit-learn offers an intuitive `explained_variance_ratio_`attribute, we can apply this concept to the previous example:\npython\n\n```\nfrom sklearn.decomposition import PCA\nfrom sklearn.datasets import make_swiss_roll\n\n# Create synthetic data\nX, t = make_swiss_roll(n_samples=1000, noise=0.2, random_state=42)\n\n# Instantiate a PCA object\npca = PCA(n_components=1)\n\n# Fit the PCA object on the data\npca.fit(X)\n\n# Calculate the EVA of each PC\neva = pca.explained_variance_ratio_\n\nprint(eva)\n```\n\nThe variance associated with the 1st principal component is about 40%. This tells us that, by reducing the original training set dimension down to just 1 feature, we are losing about 60% of the variance.\nThe most straightforward approach for choosing the number of dimension of the reduced dataset is the following: _use as many Principal Components as needed until the cumulative explained variance ratio reaches a given threshold_.\nWhile this approach may still appear obscure, an example will immediately clarify it. In this example, I will apply PCA on a synthetically generated dataset.\npython\n\n```\n# Generate the dataset\nnum_instances = 10000\nnum_features = 784\nX = np.random.rand(num_instances, num_features)\n\n# Instantiate and train a PCA object\npca = PCA()\npca.fit(X)\n\n# Compute the explained variance ratio\neva = pca.explained_variance_ratio_\n\nprint(np.round(eva, decimals=4)\n```\n\nBy printing the Explained Variance Ratio of the trained PCA, we see that the first Principale Component \"explains\" 9.75% of the variance of the original dataset, the second Principal Component is responsible for the 7.16% of the variance, and so on. After a while, the following components' explanation of the original dataset's variance becomes negligible.\n![](../images/body-6830d12d7ebd0e053776.png)\nIt's common practice to pick the Principal Components whose cumulative EVA values add up to 95% of the original dataset's variance:\n![Image by the author.](../images/body-be6d058125f2566124ab.png)\nImage by the author.\nFor the synthetic dataset, we have that 153 Principal Components are able to explain 95% of the original variance. This means that, given the 784 original features, we can safely drop 631 dimensions. In other words, we can reduce by 80% the dimension of the original training set with a cost of only 5% of lost variance.\nScikit-learn (sklearn) allows us to specify the cumulative EVA threshold we want to reach, instead of the number of Principal Components to consider:\npython\n\n```\npca = PCA(n_components=.95)\npca.fit(X)\nX_transformed = pca.transform(X)\n\nprint(X_transformed.shape)\n```\n\n![](../images/body-e8babb337026bde3a959.png)\nIn this case, we automatically get a reduced dataset made of 153 new features.\nYou can find all the code displayed in this post (and more) on this GitHub repository:\n> [**articles/dimensionality-reduction at main · andreoniriccardo/articles**](https://github.com/andreoniriccardo/articles/tree/main/dimensionality-reduction)\n## Conclusion\nIn this post, we explored the theory of this powerful, and yet simple, unsupervised model. We also understood how easy it is to implement it in Python through the Scikit-Learn library.\nUnderstanding PCA's impact on Machine Learning is essential as its applications span several industries.\nI conclude this introductory guide by delineating the pros and cons of the PCA model.\nThe main strength of PCA is its efficiency at **reducing the number of dimensions** while **retaining essential information** , lowering computation efforts, and boosting the model's performance. It is also worth noticing that PCA **decorrelates the features** , meaning that the resulting Principal Components are **statistically uncorrelated**.\nBy focusing only on the most relevant features, PCA is also able to **reduce the noise** in the original training set.\nHowever, as I mentioned earlier, PCA is not suited for every task. In some cases, like the Swiss Roll example, PCA is unable to fully capture the data structure. Applying PCA means transforming the original features into Principal Components, and consequently **losing the interpretability** of them.\nGiven these limitations, in my next post, I will deal with more complex Dimensionality Reduction algorithms like **Kernel PCA** and **LLE**.\nAs I reach the end of this guide, I need to point out that, despite having touched all the most relevant aspects of PCA, its field extends far beyond the insight provided here. For this reason, I recommend digging into the resources and references linked to this article and I encourage you to experiment with PCA on your own datasets. Your hands-on exploration will deepen your understanding, leading to valuable insights.\n* * *\nIf you liked this story, consider following me to be notified of my upcoming projects and articles!\nHere are some of my past projects:\n> [**Outlier Detection with Scikit-Learn and Matplotlib: a Practical Guide**](https://towardsdatascience.com/outlier-detection-with-scikit-learn-and-matplotlib-a-practical-guide-382d1411b8ec)\n> [**Social Network Analysis with NetworkX: A Gentle Introduction**](https://towardsdatascience.com/social-network-analysis-with-networkx-a-gentle-introduction-6123eddced3)\n## References\n  * [Principal component analysis - Wikipedia](https://en.wikipedia.org/wiki/Principal_component_analysis)\n  * [Principal component analysis - Sklearn](http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html)\n  * [Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow, 2nd Edition - Aurélien Géron](https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/)\n  * [Dive into Deep Learning - Aston Zhang, Zachary C. Lipton, Mu Li, and Alexander J. Smola](https://d2l.ai/)\n  * [A Tutorial on Principal Component Analysis - Jonathon Shlens](https://arxiv.org/abs/1404.1100)\n  * [Pattern Recognition and Machine Learning - Christopher M. Bishop](https://link.springer.com/book/9780387310732)\n\n\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](../images/body-34347b17fbf8612c4a0c.jpeg)\nWritten By\n## [Riccardo Andreoni](https://towardsdatascience.com/author/riccardo.andreoni/)\n[See all from Riccardo Andreoni](https://towardsdatascience.com/author/riccardo.andreoni/)\n[Data Science](https://towardsdatascience.com/tag/data-science/)[Dimensionality Reduction](https://towardsdatascience.com/tag/dimensionality-reduction/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Principal Component](https://towardsdatascience.com/tag/principal-component/)[Python](https://towardsdatascience.com/tag/python/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fdimensionality-reduction-made-simple-pca-theory-and-scikit-learn-implementation-9d07a388df9e%2F&title=Dimensionality%20Reduction%20Made%20Simple%3A%20PCA%20Theory%20and%20Scikit-Learn%20Implementation)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fdimensionality-reduction-made-simple-pca-theory-and-scikit-learn-implementation-9d07a388df9e%2F&title=Dimensionality%20Reduction%20Made%20Simple%3A%20PCA%20Theory%20and%20Scikit-Learn%20Implementation)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fdimensionality-reduction-made-simple-pca-theory-and-scikit-learn-implementation-9d07a388df9e%2F&text=Dimensionality%20Reduction%20Made%20Simple%3A%20PCA%20Theory%20and%20Scikit-Learn%20Implementation)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](../images/011.png)](https://towardsdatascience.com/learn-to-code-quickly-and-without-reference-through-gauntlets-3a32f79bf7db/)\n## [Learn to code quickly and without reference through gauntlets](https://towardsdatascience.com/learn-to-code-quickly-and-without-reference-through-gauntlets-3a32f79bf7db/)\n[Coding](https://towardsdatascience.com/category/programming/coding/)\nThe 10 things you need to know, with code templates in Python and R\n[Kendon Darlington](https://towardsdatascience.com/author/kendondarlington/)\nAugust 23, 20215 min read\n  * [![](../images/012.png)](https://towardsdatascience.com/what-is-business-intelligence-bf1de730319c/)\n## [What is Business Intelligence?](https://towardsdatascience.com/what-is-business-intelligence-bf1de730319c/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nDiscover the Tools for Data-Driven Decision Making Applied to Supply Chain Optimization.\n[Samir Saci](https://towardsdatascience.com/author/s-saci95/)\nAugust 4, 202310 min read\n  * [![](../images/013.jpeg)](https://towardsdatascience.com/announcing-yoltv4-improved-satellite-imagery-object-detection-f5091e913fad/)\n## [Announcing YOLTv4: Improved Satellite Imagery Object Detection](https://towardsdatascience.com/announcing-yoltv4-improved-satellite-imagery-object-detection-f5091e913fad/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nScaling advanced object detection to arbitrarily large satellite imagery\n[Adam Van Etten](https://towardsdatascience.com/author/avanetten/)\nApril 27, 20213 min read\n  * [![](../images/014.jpeg)](https://towardsdatascience.com/lessons-learned-from-my-first-1-5-years-in-industry-29d83fdf0dfb/)\n## [Lessons Learned from My First 1.5 Years in Industry](https://towardsdatascience.com/lessons-learned-from-my-first-1-5-years-in-industry-29d83fdf0dfb/)\n[Coding](https://towardsdatascience.com/category/programming/coding/)\nUnanticipated aspects of working in the tech industry from a bootcamp graduate In this article,...\n[Jesse Ruiz (she/they)](https://towardsdatascience.com/author/jjr8888/)\nApril 26, 20217 min read\n  * [![](../images/015.jpeg)](https://towardsdatascience.com/how-to-prepare-data-for-k-fold-cross-validation-in-machine-learning-924a44ec322c/)\n## [How to prepare data for K-fold cross-validation in Machine Learning](https://towardsdatascience.com/how-to-prepare-data-for-k-fold-cross-validation-in-machine-learning-924a44ec322c/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nCross-validation is the first technique to use to avoid overfitting and data leakage when we want to train a predictive model on our data.\n[Andrea D'Agostino](https://towardsdatascience.com/author/thedrewdag/)\nDecember 19, 20224 min read\n  * [![](../images/016.png)](https://towardsdatascience.com/data-visualisation-of-travel-routes-by-multiple-service-providers-on-web-app-built-with-leafletjs-dee2117647e9/)\n## [Data Visualisation of Travel Routes by Multiple Service Providers on Web App- Built with LeafletJS...](https://towardsdatascience.com/data-visualisation-of-travel-routes-by-multiple-service-providers-on-web-app-built-with-leafletjs-dee2117647e9/)\n[Web Development](https://towardsdatascience.com/category/programming/web-development/)\nWhich path is the ❝optimal route❞? Mobile responsive map layout. Full source code included.\n[Charmaine Chui](https://towardsdatascience.com/author/geek-cc/)\nAugust 3, 20224 min read\n  * [![](../images/017.jpg)](https://towardsdatascience.com/python-project-to-improve-your-productivity-for-the-new-year-1956824eddb1/)\n## [Python Project To Improve Your Productivity For The New Year!](https://towardsdatascience.com/python-project-to-improve-your-productivity-for-the-new-year-1956824eddb1/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA simple, fun, and useful Python Project developed to improve your productivity for the Upcoming New Year!\n[Bharath K](https://towardsdatascience.com/author/bharath-k1297/)\nDecember 29, 20208 min read\n  * [![](../images/018.webp)](https://towardsdatascience.com/maximizing-ai-ml-model-performance-with-pytorch-compilation/)\n## [Maximizing AI/ML Model Performance with PyTorch Compilation](https://towardsdatascience.com/maximizing-ai-ml-model-performance-with-pytorch-compilation/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nPractical Tips for Getting the Most Out of torch.compile\n[Chaim Rand](https://towardsdatascience.com/author/chaimrand/)\nAugust 18, 202526 min read\n  * [![](../images/019.png)](https://towardsdatascience.com/a-simple-guide-to-a-b-testing-in-python-5235289dae57/)\n## [A Simple Guide to A/B Testing in Python](https://towardsdatascience.com/a-simple-guide-to-a-b-testing-in-python-5235289dae57/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nWith Visualizations and Simulated Data\n[Brayton Hall](https://towardsdatascience.com/author/braytonhall/)\nSeptember 12, 20207 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n\n\n",
  "metadata": {
    "title": "Dimensionality Reduction Made Simple: PCA Theory and Scikit-Learn Implementation | Towards Data Science",
    "description": "Tame the Curse of Dimensionality! Learn Dimensionality Reduction (PCA) and implement it with Python and Scikit-Learn.",
    "keywords": null,
    "author": "Riccardo Andreoni",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Dimensionality Reduction Made Simple: PCA Theory and Scikit-Learn Implementation",
    "og:description": "Tame the Curse of Dimensionality! Learn Dimensionality Reduction (PCA) and implement it with Python and Scikit-Learn.",
    "og:url": "https://towardsdatascience.com/dimensionality-reduction-made-simple-pca-theory-and-scikit-learn-implementation-9d07a388df9e/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1178B82E2ekdUafumOV_ZbA.jpeg",
    "og:image:width": "2400",
    "og:image:height": "1204",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Riccardo Andreoni",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "11 min read",
    "article:published_time": "2024-02-07T17:57:36.000Z",
    "article:modified_time": "2024-02-07T17:57:36.000Z",
    "article:author": "https://towardsdatascience.com/author/riccardo.andreoni/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/c4a4316a40c1/code/block_000.txt",
      "chars": 480
    },
    {
      "language": "txt",
      "file": "attachments/c4a4316a40c1/code/block_001.txt",
      "chars": 425
    },
    {
      "language": "txt",
      "file": "attachments/c4a4316a40c1/code/block_002.txt",
      "chars": 354
    },
    {
      "language": "txt",
      "file": "attachments/c4a4316a40c1/code/block_003.txt",
      "chars": 282
    },
    {
      "language": "txt",
      "file": "attachments/c4a4316a40c1/code/block_004.txt",
      "chars": 100
    }
  ],
  "images": [
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:59:52Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:59:52Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:59:52Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:59:52Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/c/TowardsDataScience",
      "kind": "channel_reference",
      "status": "reference_only"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/riccardo.andreoni/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/outlier-detection-with-scikit-learn-and-matplotlib-a-practical-guide-382d1411b8ec"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/social-network-analysis-with-networkx-a-gentle-introduction-6123eddced3"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/dimensionality-reduction/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/principal-component/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/python/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/learn-to-code-quickly-and-without-reference-through-gauntlets-3a32f79bf7db/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/programming/coding/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/kendondarlington/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/what-is-business-intelligence-bf1de730319c/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/s-saci95/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://unsplash.com/photos/3DkouQeZjp4"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Flatland"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Principal_component_analysis"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/ai-data-scientist"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/machine-learning"
    },
    {
      "type": "external",
      "href": "https://scikit-learn.org/"
    },
    {
      "type": "external",
      "href": "https://pixabay.com/illustrations/universe-sky-stars-space-cosmos-2742113/"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Singular_value_decomposition"
    },
    {
      "type": "external",
      "href": "https://numpy.org/"
    },
    {
      "type": "external",
      "href": "https://github.com/andreoniriccardo/articles/tree/main/dimensionality-reduction"
    },
    {
      "type": "external",
      "href": "http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html"
    },
    {
      "type": "external",
      "href": "https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/"
    },
    {
      "type": "external",
      "href": "https://d2l.ai/"
    },
    {
      "type": "external",
      "href": "https://arxiv.org/abs/1404.1100"
    },
    {
      "type": "external",
      "href": "https://link.springer.com/book/9780387310732"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=Dimensionality+Reduction+Made+Simple%3A+PCA+Theory+and+Scikit-Learn+Implementation&u=https%3A%2F%2Ftowardsdatascience.com%2Fdimensionality-reduction-made-simple-pca-theory-and-scikit-learn-implementation-9d07a388df9e%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=Dimensionality+Reduction+Made+Simple%3A+PCA+Theory+and+Scikit-Learn+Implementation&url=https%3A%2F%2Ftowardsdatascience.com%2Fdimensionality-reduction-made-simple-pca-theory-and-scikit-learn-implementation-9d07a388df9e%2F"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:30:11Z",
  "source_url": "https://towardsdatascience.com/dimensionality-reduction-made-simple-pca-theory-and-scikit-learn-implementation-9d07a388df9e/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [],
  "expected_saved_body_images": 4,
  "image_discovery": "saved_markdown",
  "source_body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Data Science](https://towardsdatascience.com/category/data-science/)\n# Dimensionality Reduction Made Simple: PCA Theory and Scikit-Learn Implementation\nTame the Curse of Dimensionality! Learn Dimensionality Reduction (PCA) and implement it with Python and Scikit-Learn.\n[Riccardo Andreoni](https://towardsdatascience.com/author/riccardo.andreoni/)\nFebruary 7, 202411 min read\n![Image source: unsplash.com.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1178B82E2ekdUafumOV_ZbA.jpeg)\nImage source: [unsplash.com](https://unsplash.com/photos/3DkouQeZjp4).\nIn the novel [Flatland](https://en.wikipedia.org/wiki/Flatland), characters living in a two-dimensional world find themselves perplexed and unable to comprehend when they encounter a three-dimensional being. I use this analogy to illustrate how similar phenomena occur in Machine Learning when dealing with problems involving thousands or even millions of dimensions (i.e. features): **surprising phenomena happen** , which have **disastrous implications** on our Machine Learning models.\nI'm sure you felt stunned, at least once, by the **huge number of features** involved in modern Machine Learning problems. Every Data Science practitioner, sooner or later, will face this challenge. This article will explore the theoretical foundations and the Python implementation of the most used Dimensionality Reduction algorithm: [**Principal Component Analysis**](https://en.wikipedia.org/wiki/Principal_component_analysis#:~:text=Principal%20component%20analysis%20\\(PCA\\)%20is,the%20visualization%20of%20multidimensional%20data.) (PCA).\n> Why do we need to reduce the number of features?\nDatasets involving thousands or even millions of features are common nowadays. Adding new features to a dataset can bring in valuable information, however, they will **slow the training process** and make it **harder to find good patterns and solutions**. In Data Science this is called the **Curse of Dimensionality** and it often **** leads to skewed interpretation of data and inaccurate predictions.\nLearn this step by step with the interactive [AI and Data Scientist](https://roadmap.sh/ai-data-scientist) and [Machine Learning](https://roadmap.sh/machine-learning) roadmaps.\nMachine learning practitioners like us can benefit from the fact that for most ML problems, **the number of features can be reduced consistently**. For example, consider a picture: the pixels near the border often don't carry any valuable information. However, the techniques to safely reduce the number of features in a ML problem are not trivial and need an explanation that I will provide in this post.\n![Image by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1-S2LIHMEFBtybLzmANADJw.png)\nImage by the author.\nThe tools I will present not only simplify the computation effort and boost the prediction accuracy, but they will also serve as a tool to graphically visualize high-dimensional data. For this reason, they are essential to communicate your insights with other people.\nFortunately for us, the above-mentioned technique, named Dimensionality Reduction, exists and can easily take part in every data scientist's toolbox. Moreover, Dimensionality Reduction can be easily implemented in **Python** programming thanks to the [**Scikit-Learn**](https://scikit-learn.org/) (sklearn) library.\n## Curse of Dimensionality\nThe **Curse of Dimensionality** represents **one of the biggest challenges** in Data Science as it makes algorithms **computationally intensive**. But what is it exactly?\nWhen the number of dimensions in a dataset grows substantially, the available data points become sparser and sparser, leading to an intricate cascade of computational challenges. As humans, we struggle to conceptualize more than 3, or sometimes 2, dimensions. This limitation leads to very unexpected behavior of data in high-dimensional spaces.\nFor example, consider a 2D 1x1 square. If we pick a random point inside of it, there is only a small probability for it to be located very close to a border. Numerically, there is a 0.4% probability for it to be located within a 0.001 distance from a border. Instead, in a higher-dimensional unit hypercube, as the number of edges grow, the probability for a random point to be located close to a border grows exponentially. In a 10.000-dimensional hypercube, the same probability increases to over 99.99999%. This means that in a high-dimensional space, it's very **likely to be near a border**.\nThe following experiment is even **more surprising** (or disturbing in my opinion). Take the usual 2-dimensional unit square. The distance of 2 randomly chosen points inside the square is, on average, equal to 0.52. Would you believe me if I tell you that doing the same experiment with a 100.000-dimensional unit hypercube results in an average distance of 129.09? I can prove that to you with the following Montecarlo simulation.\npython\n\n```\nimport numpy as np\ntest_dimensions = [2, 100000]\nprint('Average distance between 2 points in a unit hypercube')\nfor n_dim in test_dimensions:\n    distances = []\n    for i in range(100000):\n        rand_point_1 = np.random.uniform(size=n_dim)\n        rand_point_2 = np.random.uniform(size=n_dim)\n        dist = np.linalg.norm(rand_point_1-rand_point_2)\n        distances.append(dist)\n    avg_distance = np.mean(distances)\n    print('{} dimensions: {}'.format(n_dim, avg_distance))\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1D-jvCxZby0B0KVtb9j1l0A.png)\nThe concept is even better represented by this visualization:\n![Image by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1CB1jniojRcw-x8Mo4d0lPQ.png)\nImage by the author.\nLeaving aside these funny simulations, we can extrapolate a major implication for Data Science practitioners: **there is plenty of space in high-dimensions**.\nThe consequence is that high-dimensional datasets are, with any probability, **very sparse** , and the training instances are far apart from each other. With such training data, the risk of **overfitting** your Machine Learning model is high.\nWhile, in theory, we could **add new training examples** , in practice this is not enough to cope with the increase of features. In fact, in order to maintain a constant density, the required number of training points needs to grow exponentially as a function of the number of features.\nJust to provide an example, to maintain a distance of 0.1 between each training point in a dataset with 100 features, we would need a number of training point greater than the number of atoms in the universe.\n![Image source: pixabay.com.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/12KxABAb-tN__ZMpAvKqtqg.jpeg)\nImage source: [pixabay.com](https://pixabay.com/illustrations/universe-sky-stars-space-cosmos-2742113/).\nThe only feasible approach is to **reduce the number of features** , and I will provide different techniques to do that while avoiding losing too much information.\n## Principal Component Analysis (PCA)\n[**Principal Component Analysis**](https://en.wikipedia.org/wiki/Principal_component_analysis#:~:text=Principal%20component%20analysis%20\\(PCA\\)%20is,the%20visualization%20of%20multidimensional%20data.) (**PCA**) is perhaps the most popular algorithm for Dimensionality Reduction. At its functioning core, it **projects the data onto a hyperplane** , aiming to make the rotated features statistically uncorrelated. The rotation is typically followed by selecting a subset of these new projected features, based on their importance in describing the data.\nAs PCA is based on projections, it is fundamental to know what this operation is. The following section explains the **Projection operation**.\n### Projection\nIn practical scenarios, a vast portion of the training instances lies close to a **lower-dimensional subspace** of the original training set hyperspace. The reasons are:\n  * **Correlation between features** : many features are heavily correlated.\n  * **Constant values** : many features assume near-to-constant values.\n\n\nTo illustrate this concept, take the following 2D dataset:\n![Image by the author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1-o6RMR94-LWOw3bbvAlNFw.png)\nImage by the author\nGiven the strong correlation of feature _x _1_ with feature _x _2_ , we can project the dataset on a lower-dimensional plane, which, in this case, is a line. Considering the directions identified by the black arrows, called components, if we rotate the dataset such that component 1 (_p _1_) is horizontal, we obtain:\n![Image by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1i9qPr85ZQ8yMnFPdNqg02A.png)\nImage by the author.\nAs the component _p _2_ doesn't add much information, we can project data only on component _p _1_.\n![Image by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1OHAYQbw2Xv04q48ofSrMlQ.png)\nImage by the author.\nThis is, in essence, what projection does. Its effect is even clearer considering instead a 3D dataset.\n![Image by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1eVs8iiXxATs5yaIfbsOfbQ.png)\nImage by the author.\nWe can project the original data onto a 2-dimensional plane, creating 2 new features _p _1_ , _p _2_ :\n![Image by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1B6HG-jIa38vLiIaHcTGRxQ.png)\nImage by the author.\nAs there is **no free meal in Machine Learning** , projection is not always suited for every type of dataset. If the data, in the original feature space, belong to a plane that **turns or twists** , no projection operation can preserve the original information in a lower-dimensional space.\nConsider for example the Swiss Roll dataset:\n![Image by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1uX2hMqj0BdpyYkYo4kx-Aw.png)\nImage by the author.\nIt consists of a 2D plane rolled over itself. In this case, we can't effectively project the data on a plane without losing a considerable portion of the original information.\nTo avoid this amount of information loss, we will see a different method later, which aims at \"unrolling\" the data.\n### Principal Components\nAs I anticipated, PCA consists of **projecting the data onto a lower-dimensional hyperplane**. In order to preserve as much information as possible, PCA doesn't project the data on any random hyperplane. Instead, PCA selects the hyperplane on which data projection has the **maximum variance**.\n![Image by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1JRhssojrlRBWjRiUC6W_yw.png)\nImage by the author.\nIt is easy to understand why if we consider again a 2D example.\nPCA then considers all the axes orthogonal to the one of maximum variance and selects, between them, the one with the **remaining larger variance**.\nThis process iterates as many times as the number of dimensions in the original dataset. Each identified axis is called **Principal Component** of the dataset.\nThe question now is how to mathematically compute the Principal Components. Fortunately, linear algebra provides us with the [**Singular Value Decomposition**](https://en.wikipedia.org/wiki/Singular_value_decomposition) technique, through which we can decompose the original training set _X_ into the matrix multiplication of 3 new matrices:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1f9pgm7gJADNr7ho6Cm2ESA.png)\nThe columns of the V matrix contain the direction of all the Principal Components previously identified.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1tuJvmAupudBbUdjb3sPhMg.png)\nWhile it is easy to implement SVD with the [Numpy](https://numpy.org/) Python library, it is even more effortless to implement PCA with the [Scikit-learn](https://scikit-learn.org/) (sklearn) module.\nIn Scikit-learn (sklearn) I first need to create a `PCA()` object, and later fit it on the data and transform them:\npython\n\n```\nfrom sklearn.decomposition import PCA\nfrom sklearn.datasets import make_swiss_roll\n\n# Create synthetic data\nX, t = make_swiss_roll(n_samples=1000, noise=0.2, random_state=42)\n\n# Instantiate a PCA object\npca = PCA(n_components=1)\n\n# Fit the PCA object on the data\npca.fit(X)\n\n# Transform the data\nX_transformed = pca.transform(X)\n\nprint('Original data shape: ', X.shape)\nprint('Transformed data shape: ', X_transformed.shape)\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1FDlENY0m2h2Rw5-dTH63Dg.png)\nAs we can see from the output, we reduced the original dataset dimension from 3 down to 1 dimension. This happened because we specified `n_components=1` while instantiating the `PCA()` object.\nUnless we are performing Dimensionality Reduction for **data visualization** , we might not know which is the best number of dimensions of the transformed training set.\n**Selecting the right number of dimensions** to reduce the training set down to is a big deal in Dimensionality Reduction. If the original feature space is narrow, we might try a manual iterative approach, However, in most real-world cases, the feature space is huge and we need a more robust and automized approach.\nIn order to introduce said approach, I first need to define the **Explained Variance Ratio** (EVR). In simple terms, the EVR is defined as the percentage of the variance of the original dataset which lies along each Principal Component.\nAs Scikit-learn offers an intuitive `explained_variance_ratio_`attribute, we can apply this concept to the previous example:\npython\n\n```\nfrom sklearn.decomposition import PCA\nfrom sklearn.datasets import make_swiss_roll\n\n# Create synthetic data\nX, t = make_swiss_roll(n_samples=1000, noise=0.2, random_state=42)\n\n# Instantiate a PCA object\npca = PCA(n_components=1)\n\n# Fit the PCA object on the data\npca.fit(X)\n\n# Calculate the EVA of each PC\neva = pca.explained_variance_ratio_\n\nprint(eva)\n```\n\nThe variance associated with the 1st principal component is about 40%. This tells us that, by reducing the original training set dimension down to just 1 feature, we are losing about 60% of the variance.\nThe most straightforward approach for choosing the number of dimension of the reduced dataset is the following: _use as many Principal Components as needed until the cumulative explained variance ratio reaches a given threshold_.\nWhile this approach may still appear obscure, an example will immediately clarify it. In this example, I will apply PCA on a synthetically generated dataset.\npython\n\n```\n# Generate the dataset\nnum_instances = 10000\nnum_features = 784\nX = np.random.rand(num_instances, num_features)\n\n# Instantiate and train a PCA object\npca = PCA()\npca.fit(X)\n\n# Compute the explained variance ratio\neva = pca.explained_variance_ratio_\n\nprint(np.round(eva, decimals=4)\n```\n\nBy printing the Explained Variance Ratio of the trained PCA, we see that the first Principale Component \"explains\" 9.75% of the variance of the original dataset, the second Principal Component is responsible for the 7.16% of the variance, and so on. After a while, the following components' explanation of the original dataset's variance becomes negligible.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1aMQ7sT4Ez77wkn9VONTM-Q.png)\nIt's common practice to pick the Principal Components whose cumulative EVA values add up to 95% of the original dataset's variance:\n![Image by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/13BRlzLt70FZ7ABiTK94Rzg.png)\nImage by the author.\nFor the synthetic dataset, we have that 153 Principal Components are able to explain 95% of the original variance. This means that, given the 784 original features, we can safely drop 631 dimensions. In other words, we can reduce by 80% the dimension of the original training set with a cost of only 5% of lost variance.\nScikit-learn (sklearn) allows us to specify the cumulative EVA threshold we want to reach, instead of the number of Principal Components to consider:\npython\n\n```\npca = PCA(n_components=.95)\npca.fit(X)\nX_transformed = pca.transform(X)\n\nprint(X_transformed.shape)\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1IYnzW8n0-puXeX74Ubo3ow.png)\nIn this case, we automatically get a reduced dataset made of 153 new features.\nYou can find all the code displayed in this post (and more) on this GitHub repository:\n> [**articles/dimensionality-reduction at main · andreoniriccardo/articles**](https://github.com/andreoniriccardo/articles/tree/main/dimensionality-reduction)\n## Conclusion\nIn this post, we explored the theory of this powerful, and yet simple, unsupervised model. We also understood how easy it is to implement it in Python through the Scikit-Learn library.\nUnderstanding PCA's impact on Machine Learning is essential as its applications span several industries.\nI conclude this introductory guide by delineating the pros and cons of the PCA model.\nThe main strength of PCA is its efficiency at **reducing the number of dimensions** while **retaining essential information** , lowering computation efforts, and boosting the model's performance. It is also worth noticing that PCA **decorrelates the features** , meaning that the resulting Principal Components are **statistically uncorrelated**.\nBy focusing only on the most relevant features, PCA is also able to **reduce the noise** in the original training set.\nHowever, as I mentioned earlier, PCA is not suited for every task. In some cases, like the Swiss Roll example, PCA is unable to fully capture the data structure. Applying PCA means transforming the original features into Principal Components, and consequently **losing the interpretability** of them.\nGiven these limitations, in my next post, I will deal with more complex Dimensionality Reduction algorithms like **Kernel PCA** and **LLE**.\nAs I reach the end of this guide, I need to point out that, despite having touched all the most relevant aspects of PCA, its field extends far beyond the insight provided here. For this reason, I recommend digging into the resources and references linked to this article and I encourage you to experiment with PCA on your own datasets. Your hands-on exploration will deepen your understanding, leading to valuable insights.\n* * *\nIf you liked this story, consider following me to be notified of my upcoming projects and articles!\nHere are some of my past projects:\n> [**Outlier Detection with Scikit-Learn and Matplotlib: a Practical Guide**](https://towardsdatascience.com/outlier-detection-with-scikit-learn-and-matplotlib-a-practical-guide-382d1411b8ec)\n> [**Social Network Analysis with NetworkX: A Gentle Introduction**](https://towardsdatascience.com/social-network-analysis-with-networkx-a-gentle-introduction-6123eddced3)\n## References\n  * [Principal component analysis - Wikipedia](https://en.wikipedia.org/wiki/Principal_component_analysis)\n  * [Principal component analysis - Sklearn](http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html)\n  * [Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow, 2nd Edition - Aurélien Géron](https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/)\n  * [Dive into Deep Learning - Aston Zhang, Zachary C. Lipton, Mu Li, and Alexander J. Smola](https://d2l.ai/)\n  * [A Tutorial on Principal Component Analysis - Jonathon Shlens](https://arxiv.org/abs/1404.1100)\n  * [Pattern Recognition and Machine Learning - Christopher M. Bishop](https://link.springer.com/book/9780387310732)\n\n\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657095428_xaezyc.jpeg)\nWritten By\n## [Riccardo Andreoni](https://towardsdatascience.com/author/riccardo.andreoni/)\n[See all from Riccardo Andreoni](https://towardsdatascience.com/author/riccardo.andreoni/)\n[Data Science](https://towardsdatascience.com/tag/data-science/)[Dimensionality Reduction](https://towardsdatascience.com/tag/dimensionality-reduction/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Principal Component](https://towardsdatascience.com/tag/principal-component/)[Python](https://towardsdatascience.com/tag/python/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fdimensionality-reduction-made-simple-pca-theory-and-scikit-learn-implementation-9d07a388df9e%2F&title=Dimensionality%20Reduction%20Made%20Simple%3A%20PCA%20Theory%20and%20Scikit-Learn%20Implementation)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fdimensionality-reduction-made-simple-pca-theory-and-scikit-learn-implementation-9d07a388df9e%2F&title=Dimensionality%20Reduction%20Made%20Simple%3A%20PCA%20Theory%20and%20Scikit-Learn%20Implementation)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fdimensionality-reduction-made-simple-pca-theory-and-scikit-learn-implementation-9d07a388df9e%2F&text=Dimensionality%20Reduction%20Made%20Simple%3A%20PCA%20Theory%20and%20Scikit-Learn%20Implementation)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/08/1wiu9k3FNgXpNofP5ZxFv-Q.png)](https://towardsdatascience.com/learn-to-code-quickly-and-without-reference-through-gauntlets-3a32f79bf7db/)\n## [Learn to code quickly and without reference through gauntlets](https://towardsdatascience.com/learn-to-code-quickly-and-without-reference-through-gauntlets-3a32f79bf7db/)\n[Coding](https://towardsdatascience.com/category/programming/coding/)\nThe 10 things you need to know, with code templates in Python and R\n[Kendon Darlington](https://towardsdatascience.com/author/kendondarlington/)\nAugust 23, 20215 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1jBoslFtpH_AMnB3a34z6XA.png)](https://towardsdatascience.com/what-is-business-intelligence-bf1de730319c/)\n## [What is Business Intelligence?](https://towardsdatascience.com/what-is-business-intelligence-bf1de730319c/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nDiscover the Tools for Data-Driven Decision Making Applied to Supply Chain Optimization.\n[Samir Saci](https://towardsdatascience.com/author/s-saci95/)\nAugust 4, 202310 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1I5x4dVSdLmZ50iEHkkRAqw.jpeg)](https://towardsdatascience.com/announcing-yoltv4-improved-satellite-imagery-object-detection-f5091e913fad/)\n## [Announcing YOLTv4: Improved Satellite Imagery Object Detection](https://towardsdatascience.com/announcing-yoltv4-improved-satellite-imagery-object-detection-f5091e913fad/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nScaling advanced object detection to arbitrarily large satellite imagery\n[Adam Van Etten](https://towardsdatascience.com/author/avanetten/)\nApril 27, 20213 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1f775bVj1p4DhrWGGbcKCUg-scaled.jpeg)](https://towardsdatascience.com/lessons-learned-from-my-first-1-5-years-in-industry-29d83fdf0dfb/)\n## [Lessons Learned from My First 1.5 Years in Industry](https://towardsdatascience.com/lessons-learned-from-my-first-1-5-years-in-industry-29d83fdf0dfb/)\n[Coding](https://towardsdatascience.com/category/programming/coding/)\nUnanticipated aspects of working in the tech industry from a bootcamp graduate In this article,...\n[Jesse Ruiz (she/they)](https://towardsdatascience.com/author/jjr8888/)\nApril 26, 20217 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/12/15Qy406_ubijCkT5yXord8w.jpeg)](https://towardsdatascience.com/how-to-prepare-data-for-k-fold-cross-validation-in-machine-learning-924a44ec322c/)\n## [How to prepare data for K-fold cross-validation in Machine Learning](https://towardsdatascience.com/how-to-prepare-data-for-k-fold-cross-validation-in-machine-learning-924a44ec322c/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nCross-validation is the first technique to use to avoid overfitting and data leakage when we want to train a predictive model on our data.\n[Andrea D'Agostino](https://towardsdatascience.com/author/thedrewdag/)\nDecember 19, 20224 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/08/1ptLFkzPbmNjl5LJv9MRrUQ.png)](https://towardsdatascience.com/data-visualisation-of-travel-routes-by-multiple-service-providers-on-web-app-built-with-leafletjs-dee2117647e9/)\n## [Data Visualisation of Travel Routes by Multiple Service Providers on Web App- Built with LeafletJS...](https://towardsdatascience.com/data-visualisation-of-travel-routes-by-multiple-service-providers-on-web-app-built-with-leafletjs-dee2117647e9/)\n[Web Development](https://towardsdatascience.com/category/programming/web-development/)\nWhich path is the ❝optimal route❞? Mobile responsive map layout. Full source code included.\n[Charmaine Chui](https://towardsdatascience.com/author/geek-cc/)\nAugust 3, 20224 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/12/0GSD_sEMm-8CvhuS5-scaled.jpg)](https://towardsdatascience.com/python-project-to-improve-your-productivity-for-the-new-year-1956824eddb1/)\n## [Python Project To Improve Your Productivity For The New Year!](https://towardsdatascience.com/python-project-to-improve-your-productivity-for-the-new-year-1956824eddb1/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA simple, fun, and useful Python Project developed to improve your productivity for the Upcoming New Year!\n[Bharath K](https://towardsdatascience.com/author/bharath-k1297/)\nDecember 29, 20208 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/08/1.webp)](https://towardsdatascience.com/maximizing-ai-ml-model-performance-with-pytorch-compilation/)\n## [Maximizing AI/ML Model Performance with PyTorch Compilation](https://towardsdatascience.com/maximizing-ai-ml-model-performance-with-pytorch-compilation/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nPractical Tips for Getting the Most Out of torch.compile\n[Chaim Rand](https://towardsdatascience.com/author/chaimrand/)\nAugust 18, 202526 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/09/1m1jiK0O9zg0DyjGL7Q8spg.png)](https://towardsdatascience.com/a-simple-guide-to-a-b-testing-in-python-5235289dae57/)\n## [A Simple Guide to A/B Testing in Python](https://towardsdatascience.com/a-simple-guide-to-a-b-testing-in-python-5235289dae57/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nWith Visualizations and Simulated Data\n[Brayton Hall](https://towardsdatascience.com/author/braytonhall/)\nSeptember 12, 20207 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n\n\n",
  "body_base_path": "attachments/c4a4316a40c1/pages/",
  "body_markdown_path": "attachments/c4a4316a40c1/pages/archived-body.md",
  "local_html": "attachments/c4a4316a40c1/pages/archived-body.html",
  "body_source": "prior_capture"
}