{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Ingo Nowitzky",
  "title_listed": "Linear Discriminant Analysis (LDA)",
  "keywords": "",
  "domain": "机器学习",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/linear-discriminant-analysis-lda-598d8e90f8b9/",
  "publish_date": "2024-10-12",
  "corpus_stage": "",
  "notes": "",
  "id": "2581fb17d313",
  "collected_at": "2026-10-02T10:16:02",
  "title": "Linear Discriminant Analysis (LDA) | 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[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\n# Linear Discriminant Analysis (LDA)\nDiscover how LDA helps identify critical data features\n[Ingo Nowitzky](https://towardsdatascience.com/author/ingo.nowitzky/)\nOctober 12, 202412 min read\n![Classification of LDA within AI and ML Methods | image by author](../images/000.png)\nClassification of LDA within AI and ML Methods | image by author\n**This article aims to explore Linear Discriminant Analysis (LDA), focusing on its core ideas, its mathematical implementation in code, and a practical example from manufacturing. I hope you're on board. Let's get started!**\nWho works with **industrial data** in practice will be familiar with this situation: The datasets usually have many features, and it is often unclear which of the features are important and which are less. \"Important\" is a relative term in this context. Often, the goal is to differentiate the datasets from each other, i.e., to classify them. A very typical task is to distinguish good parts from bad parts and to identify the causes (aka features) that lead to the failure of the parts.\nA commonly used method is the well-known Principal Component Analysis (PCA). While PCA belongs to the **un** supervised methods, the less widespread LDA is a supervised method and thus learns from **labeled data**. Therefore, it is particularly suited for explaining failure patterns from large datasets.\nLearn this step by step with the interactive [Machine Learning](https://roadmap.sh/machine-learning) roadmap.\n## 1. Goal and Principle of LDA\nThe goal of LDA is to linearly combine the features of the data so that the labels of the datasets are best separated from each other, and the number of new features is reduced to a predefined count. In AI jargon, this is typically referred to as a **projection to a lower-dimensional space**.\n![Principle of LDA | image modified from Raschka/Mirjalili, 2019](../images/001.png)\nPrinciple of LDA | image modified from [Raschka/Mirjalili, 2019](https://github.com/rasbt/python-machine-learning-book-3rd-edition/blob/master/ch05/images/05_06.png)\n## Excursus: What is dimensionality and what is dimensionality reduction?\n![Dimensions and graphical representation | image by author](../images/002.png)\nDimensions and graphical representation | image by author\nDimensionality refers to the number of features in a dataset. With just one measurement (or feature), such as the tool temperature from an injection molding machine, we can represent it on a number line. Two features, like temperature and tool pressure, are still manageable: we can easily plot the data on an x-y chart. With three features - temperature, tool pressure, and injection pressure - things get more interesting, but we can still plot the data in a 3D x-y-z chart. However, when we add more features, such as viscosity, electrical conductivity, and others, the complexity increases.\n![Dimensionality reduction | image by author](../images/003.png)\nDimensionality reduction | image by author\nIn practice, datasets often contain hundreds or even thousands of features. This presents a challenge because many machine learning algorithms perform poorly as datasets grow too large. Additionally, the amount of data required increases exponentially with the number of dimensions to achieve statistical significance. This phenomenon is known as the \"curse of dimensionality.\" These factors make it essential to determine which features are relevant and to eliminate the less meaningful ones early in the data science process.\n## 2. How does LDA work?\nThe process of Linear Discriminant Analysis (LDA) can be broken down into five key steps.\n**Step 1:** Compute the _d_ -dimensional mean vectors for each of the _k_ classes separately from the dataset.\nRemember that LDA is a supervised machine learning technique, meaning we can utilize the known labels. In the first step, we calculate the mean vectors _mean _c_ for all samples belonging to a specific class _c_. To do this, we filter the feature matrix by class label and compute the mean for each of the _d_ features. As a result, we obtain _k_ mean vectors (one for each of the _k_ classes), each with a length of _d_ (corresponding to the _d_ features).\n![Label vector Y and feature matrix X | image by author](../images/004.png)\nLabel vector Y and feature matrix X | image by author\n**Step 2:** Compute the scatter matrices (between-class scatter matrix and within-class scatter matrix).\nThe within-class scatter matrix measures the variation among samples within the same class. To find a subspace with optimal separability, we aim to minimize the values in this matrix. In contrast, the between-class scatter matrix measures the variation between different classes. For optimal separability, we aim to maximize the values in this matrix. Intuitively, within-class scatter looks at how compact each class is, whereas between-class scatter examines how far apart different classes are.\n![Within-class and between-class scatter matrices | image by author](../images/005.png)\nWithin-class and between-class scatter matrices | image by author\nLet's start with the **within-class scatter** matrix _S _W_. It is calculated as the sum of the scatter matrices _S _c_ for each individual class:\nThe **between-class scatter** matrix _S _B_ is derived from the differences between the class means _mean _c_ and the overall mean of the entire dataset:\nwhere _mean_ refers to the mean vector calculated over all samples, regardless of their class labels.\n**Step 3:** Calculate the eigenvectors and eigenvalues for the ratio of _S _W_ ​ and _S _B_ ​.\nAs mentioned, for optimal class separability, we aim to maximize _S _B​_ and minimize _S _W_ ​. We can achieve both by maximizing the ratio _S_B/S _W_ ​. In linear algebra terms, this ratio corresponds to the scatter matrix _S_W⁻¹ S _B_ ​, which is maximized in the subspace spanned by the eigenvectors with the highest eigenvalues. The eigenvectors define the directions of this subspace, while the eigenvalues represent the magnitude of the distortion. We will select the _m_ eigenvectors associated with the highest eigenvalues.\n![Subspace spanned by eigenvectors | image by author](../images/006.png)\nSubspace spanned by eigenvectors | image by author\n**Step 4:** Sort the eigenvectors in descending order of their corresponding eigenvalues, and select the _m_ eigenvectors with the largest eigenvalues to form a _d × m-_dimensional transformation matrix _W_.\nRemember, our goal is not only to project the data into a subspace that enhances class separability but also to reduce dimensionality. The eigenvectors will define the axes of our new feature subspace. To decide which eigenvectors to discard for the lower-dimensional subspace, we need to examine their corresponding eigenvalues. In simple terms, the eigenvectors with the smallest eigenvalues contribute the least to class separation, and these are the ones we want to drop. The typical approach is to rank the eigenvalues in descending order and select the top _m_ eigenvectors. _m_ is a freely chosen parameter. The larger _m_ , the less information is lost during the transformation.\nAfter sorting the eigenpairs by decreasing eigenvalues and selecting the top _m_ pairs, the next step is to construct the _d × m_ -dimensional transformation matrix _W_. This is done by stacking the _m_ selected eigenvectors horizontally, resulting in the matrix _W_ :\nThe first column of _W_ represents the eigenvector corresponding to the highest eigenvalue, the second column represents the eigenvector corresponding to the second highest eigenvalue, and so on.\n**Step 5:** Use _W_ to project the samples onto the new subspace.\nIn the final step, we use the _d × m-_dimensional transformation matrix _W_ , which we composed from the top _m_ selected eigenvectors, to project our samples onto the new subspace:\nwhere _X_ is the initial _n × d_ -dimensional feature matrix representing our samples, and _Z_ is the newly transformed _n × m_ -dimensional feature matrix in the new subspace. This means that the selected eigenvectors serve as the \"recipes\" for transforming the original features into the new features (the **Linear Discriminants**): The eigenvector with the highest eigenvalue provides the transformation recipe for **LD1** , the eigenvector with the second highest eigenvalue corresponds to **LD2** , and so on.\n![Projection of X onto the linear discriminants LD](../images/007.png)\nProjection of X onto the linear discriminants LD\n## 3. Implementing Linear Discriminant Analysis (LDA) from Scratch\nTo demonstrate the theory and mathematics in action, we will program our own LDA from scratch using only numpy.\npython\n\n```\nimport numpy as np\n\nclass LDA_fs:\n    \"\"\"\n    Performs a Linear Discriminant Analysis (LDA)\n\n    Methods\n    =======\n    fit_transform():\n        Fits the model to the data X and Y, derives the transformation matrix W\n    and projects the feature matrix X onto the m LDA axes\n    \"\"\"\n\n    def __init__(self, m):\n        \"\"\"\n        Parameters\n        ==========\n        m : int\n            Number of LDA axes onto which the data will be projected\n\n        Returns\n        =======\n        None\n        \"\"\"\n        self.m = m\n\n    def fit_transform(self, X, Y):\n        \"\"\"\n        Parameters\n        ==========\n        X : array(n_samples, n_features)\n            Feature matrix of the dataset\n        Y = array(n_samples)\n            Label vector of the dataset\n\n        Returns\n        =======\n        X_transform : New feature matrix projected onto the m LDA axes\n\n        \"\"\"\n\n        # Get number of features (columns)\n        self.n_features = X.shape[1]\n        # Get unique class labels\n        class_labels = np.unique(Y)\n        # Get the overall mean vector (independent of the class labels)\n        mean_overall = np.mean(X, axis=0)  # Mean of each feature\n        # Initialize both scatter matrices with zeros\n        SW = np.zeros((self.n_features, self.n_features))  # Within scatter matrix\n        SB = np.zeros((self.n_features, self.n_features))  # Between scatter matrix\n\n        # Iterate over all classes and select the corresponding data\n        for c in class_labels:\n            # Filter X for class c\n            X_c = X[Y == c]\n            # Calculate the mean vector for class c\n            mean_c = np.mean(X_c, axis=0)\n            # Calculate within-class scatter for class c\n            SW += (X_c - mean_c).T.dot((X_c - mean_c))\n            # Number of samples in class c\n            n_c = X_c.shape[0]\n            # Difference between the overall mean and the mean of class c --> between-class scatter\n            mean_diff = (mean_c - mean_overall).reshape(self.n_features, 1)\n            SB += n_c * (mean_diff).dot(mean_diff.T)\n\n        # Determine SW^-1 * SB\n        A = np.linalg.inv(SW).dot(SB)\n        # Get the eigenvalues and eigenvectors of (SW^-1 * SB)\n        eigenvalues, eigenvectors = np.linalg.eig(A)\n        # Keep only the real parts of eigenvalues and eigenvectors\n        eigenvalues = np.real(eigenvalues)\n        eigenvectors = np.real(eigenvectors.T)\n\n        # Sort the eigenvalues descending (high to low)\n        idxs = np.argsort(np.abs(eigenvalues))[::-1]\n        self.eigenvalues = np.abs(eigenvalues[idxs])\n        self.eigenvectors = eigenvectors[idxs]\n        # Store the first m eigenvectors as transformation matrix W\n        self.W = self.eigenvectors[0:self.m]\n\n        # Transform the feature matrix X onto LD axes\n        return np.dot(X, self.W.T)\n```\n\n## 4. Applying LDA to an Industrial Dataset\nTo see LDA in action, we will apply it to a typical task in the production environment. We have data from a simple manufacturing line with only 7 stations. Each of these stations sends a data point (yes, I know, only one data point is highly unrealistic). Unfortunately, our line produces a significant number of defective parts, and we want to find out which stations are responsible for this.\nFirst, we load the data and take an initial look.\npython\n\n```\nimport pandas as pd\n\n# URL to Github repository\nurl = \"https://raw.githubusercontent.com/IngoNowitzky/LDA_Medium/main/production_line_data.csv\"\n\n# Read csv to DataFrame\ndata = pd.read_csv(url)\n\n# Print first 5 lines\ndata.head()\n```\n\n![](../images/body-6858970063639e1fcac2.png)\nNext, we study the distribution of the data using the `.describe()` method from Pandas.\npython\n\n```\n# Show average, min and max of numerical values\ndata.describe()\n```\n\n![](../images/body-477c5d362bddf49fac69.png)\nWe see that we have 20,000 data points, and the measurements range from -5 to +150. Hence, we note for later that we need to normalize the dataset: the different magnitudes of the numerical values would otherwise negatively affect the LDA. How many good parts and how many bad parts do we have?\npython\n\n```\n# Count the number of good and bad parts\nlabel_counts = data['Label'].value_counts()\n\n# Display the results\nprint(\"Number of Good and Bad Parts:\")\nprint(label_counts)\n```\n\n![](../images/body-567d13c591762ba79fb7.png)\nWe have 19,031 good parts and 969 defective parts. The fact that the dataset is so imbalanced is an issue for further analysis. Therefore, we select all defective parts and an equal number of randomly chosen good parts for the further processing.\npython\n\n```\n# Select all bad parts\nbad_parts = data[data['Label'] == 'Bad']\n\n# Randomly select an equal number of good parts\ngood_parts = data[data['Label'] == 'Good'].sample(n=len(bad_parts), random_state=42)\n\n# Combine both subsets to create a balanced dataset\nbalanced_data = pd.concat([bad_parts, good_parts])\n\n# Shuffle the combined dataset\nbalanced_data = balanced_data.sample(frac=1, random_state=42).reset_index(drop=True)\n\n# Display the number of good and bad parts in the balanced dataset\nprint(\"Number of Good and Bad Parts in the balanced dataset:\")\nprint(balanced_data['Label'].value_counts())\n```\n\n![](../images/body-0f452a4594e8f7500628.png)\nNow, let's apply our LDA from scratch to the balanced dataset. We use the `StandardScaler` from `sklearn` to normalize the measurements for each feature to have a mean of 0 and a standard deviation of 1. We choose only one linear discriminant axis (_m=1_) onto which we project the data. This helps us clearly see which features are most relevant in distinguishing good from bad parts, and we visualize the projected data in a histogram.\npython\n\n```\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler\n\n# Separate features and labels\nX = balanced_data.drop(columns=['Label'])\ny = balanced_data['Label']\n\n# Normalize the features\nscaler = StandardScaler()\nX_scaled = scaler.fit_transform(X)\n\n# Perform LDA\nlda = LDA_fs(m=1)  # Instanciate LDA object with 1 axis\nX_lda = lda.fit_transform(X_scaled, y) # Fit the model and project the data\n\n# Plot the LDA projection\nplt.figure(figsize=(10, 6))\nplt.hist(X_lda[y == 'Good'], bins=20, alpha=0.7, label='Good', color='green')\nplt.hist(X_lda[y == 'Bad'], bins=20, alpha=0.7, label='Bad', color='red')\nplt.title(\"LDA Projection of Good and Bad Parts\")\nplt.xlabel(\"LDA Component\")\nplt.ylabel(\"Frequency\")\nplt.legend()\nplt.show()\n\n# Examine feature contributions to the LDA component\nfeature_importance = pd.DataFrame({'Feature': X.columns, 'LDA Coefficient': lda.W[0]})\nfeature_importance = feature_importance.sort_values(by='LDA Coefficient', ascending=False)\n\n# Display feature importance\nprint(\"Feature Contributions to LDA Component:\")\nprint(feature_importance)\n```\n\n![Feature matrix projected to one LD \\(m=1\\)](../images/008.png)\nFeature matrix projected to one LD (m=1)\n![Feature importance = How much do the stations contribute to class separation?](../images/body-62fadbb0aaad1b184101.png)\nFeature importance = How much do the stations contribute to class separation?\nThe histogram shows that we can separate the good parts from the defective parts very well, with only a small overlap. This is already a positive result and indicates that our LDA was successful.\nThe \"LDA Coefficients\" from the table \"Feature Contributions to LDA Components\" represent the eigenvector from the first (and only, since _m=1_) column of our transformation matrix _W_. They indicate the direction and magnitude with which the normalized measurements from the stations are projected onto the linear discriminant axis. The values in the table are sorted in descending order. We need to read the table from both the top and the bottom simultaneously because the absolute value of the coefficient indicates the significance of each station in separating the classes and, consequently, its contribution to the production of defective parts. The sign indicates whether a lower or higher measurement increases the likelihood of defective parts. Let's take a closer look at our example:\nThe largest absolute value is from Station 4, with a coefficient of -0.672. This means that Station 4 has the strongest influence on part failure. Due to the negative sign, higher positive measurements are projected towards a negative linear discriminant (LD). The histogram shows that a negative LD is associated with good (green) parts. Conversely, **low and negative measurements at this station increase the likelihood of part failure**. The second highest absolute value is from Station 2, with a coefficient of 0.557. Therefore, this station is the second most significant contributor to part failures. The positive sign indicates that high positive measurements are projected towards the positive LD. From the histogram, we know that a high positive LD value is associated with a high likelihood of failure. In other words, **high measurements at Station 2 lead to part failures**. The third highest coefficient comes from Station 7, with a value of -0.486. This makes Station 7 the third largest contributor to part failures. The negative sign again indicates that high positive values at this station lead to a negative LD (which corresponds to good parts). Conversely, **low and negative values at this station lead to part failures**. All other LDA coefficients are an order of magnitude smaller than the three mentioned, **the associated stations therefore have no influence on part failure**.\nAre the results of our LDA analysis correct? As you may have already guessed, the production dataset is synthetically generated. I labeled all parts as defective where the measurement at Station 2 was greater than 0.5, the value at Station 4 was less than -2.5, and the value at Station 7 was less than 3. **It turns out that the LDA hit the mark perfectly!**\npython\n\n```\n# Determine if a sample is a good or bad part based on the conditions\ndata['Label'] = np.where(\n    (data['Station_2'] > 0.5) &amp; (data['Station_4'] < -2.5) &amp; (data['Station_7'] < 3),\n    'Bad',\n    'Good'\n)\n```\n\n## 5. Conclusion\nLinear Discriminant Analysis (LDA) not only reduces the complexity of datasets but also highlights the key features that drive class separation, making it highly effective for identifying failure causes in production systems. It is a straightforward yet powerful method with practical applications and is readily available in libraries like `scikit-learn`.\nTo achieve optimal results, it is crucial to balance the dataset (ensure a similar number of samples in each class) and normalize it (mean of 0 and standard deviation of 1). **The next time you work with a large dataset containing class labels and numerous features, why not give LDA a try?**\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-f5a06262cccdb3c06ef7.jpeg)\nWritten By\n## [Ingo Nowitzky](https://towardsdatascience.com/author/ingo.nowitzky/)\nPhD Engineer, Lean Production professional, and AI enthisiast.\n[See all from Ingo Nowitzky](https://towardsdatascience.com/author/ingo.nowitzky/)\n[class-separation](https://towardsdatascience.com/tag/class-separation/)[Data Preparation](https://towardsdatascience.com/tag/data-preparation/)[Dimensionality Reduction](https://towardsdatascience.com/tag/dimensionality-reduction/)[Failure Detection](https://towardsdatascience.com/tag/failure-detection/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Flinear-discriminant-analysis-lda-598d8e90f8b9%2F&title=Linear%20Discriminant%20Analysis%20\\(LDA\\))\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Flinear-discriminant-analysis-lda-598d8e90f8b9%2F&title=Linear%20Discriminant%20Analysis%20\\(LDA\\))\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Flinear-discriminant-analysis-lda-598d8e90f8b9%2F&text=Linear%20Discriminant%20Analysis%20\\(LDA\\))\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/009.png)](https://towardsdatascience.com/controlling-a-mouse-with-your-eyes-f1097e7cf2e9/)\n## [Controlling a Mouse With Your Eyes](https://towardsdatascience.com/controlling-a-mouse-with-your-eyes-f1097e7cf2e9/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA Machine Learning approach to eye pose estimation from just a single front-facing perspective as input.\n[Ryan Rudes](https://towardsdatascience.com/author/ryanrudes/)\nSeptember 21, 20207 min read\n  * [![](../images/010.jpg)](https://towardsdatascience.com/forecasting-with-granger-causality-checking-for-time-series-spurious-correlations-5faed62c3604/)\n## [Forecasting with Granger Causality: Checking for Time Series Spurious Correlations](https://towardsdatascience.com/forecasting-with-granger-causality-checking-for-time-series-spurious-correlations-5faed62c3604/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nHacking Granger Causality Test with ML Approaches\n[Marco Cerliani](https://towardsdatascience.com/author/cerlymarco/)\nApril 6, 20235 min read\n  * [![](../images/011.png)](https://towardsdatascience.com/facebooks-data-science-interview-practice-problems-46c7263709bf/)\n## [Facebook's Data Science Interview Practice Problems](https://towardsdatascience.com/facebooks-data-science-interview-practice-problems-46c7263709bf/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA walkthrough of some of Facebook's interview questions!\n[Terence Shin, MSc, MBA](https://towardsdatascience.com/author/terenceshin/)\nMarch 8, 20208 min read\n  * [![](../images/012.jpg)](https://towardsdatascience.com/why-gradient-descent-works-4e487d3c84c1/)\n## [Why Gradient Descent Works?](https://towardsdatascience.com/why-gradient-descent-works-4e487d3c84c1/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nEverybody knows what Gradient Descent is and how it works. Ever wondered why it works? Here's a mathematical explanation\n[Kunj Mehta](https://towardsdatascience.com/author/kunjmehta10/)\nOctober 20, 20214 min read\n  * [![](../images/013.jpeg)](https://towardsdatascience.com/putting-your-models-into-production-5ae3191722b9/)\n## [Putting Your Models Into Production](https://towardsdatascience.com/putting-your-models-into-production-5ae3191722b9/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nA guide to getting your deep learning model into production with TensorFlow Serving.\n[Zito Relova](https://towardsdatascience.com/author/zito-relova/)\nApril 13, 20214 min read\n  * [![](../images/014.png)](https://towardsdatascience.com/why-is-cross-entropy-equal-to-kl-divergence-d4d2ec413864/)\n## [Why Is Cross Entropy Equal to KL-Divergence?](https://towardsdatascience.com/why-is-cross-entropy-equal-to-kl-divergence-d4d2ec413864/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nIt is a common practice to use cross-entropy in the loss function while constructing a Generative Adversarial Network [1] even though...\n[J. Rafid Siddiqui, PhD](https://towardsdatascience.com/author/azad-wolf/)\nFebruary 6, 20223 min read\n  * [![](../images/015.png)](https://towardsdatascience.com/the-math-thats-killing-your-ai-agent/)\n## [The Math That’s Killing Your AI Agent](https://towardsdatascience.com/the-math-thats-killing-your-ai-agent/)\n[Agentic AI](https://towardsdatascience.com/category/artificial-intelligence/agentic-ai/)\nAn 85% accurate agent fails four out of five times on a 10-step task. Here's the arithmetic nobody runs before deploying.\n[Kaushik Rajan](https://towardsdatascience.com/author/kaushikvr06/)\nMarch 20, 202611 min read\n  * [![](../images/016.png)](https://towardsdatascience.com/from-research-to-production-with-deep-semi-supervised-learning-7caaedc39093/)\n## [From Research to Production with Deep Semi-Supervised Learning](https://towardsdatascience.com/from-research-to-production-with-deep-semi-supervised-learning-7caaedc39093/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nSemi-Supervised Learning (SSL) has blossomed in the deep learning research community - we share lessons learned taking SSL into production.\n[Varun Nair](https://towardsdatascience.com/author/nairvarun/)\nSeptember 25, 202016 min read\n  * [![](../images/017.jpg)](https://towardsdatascience.com/using-mlflow-to-track-machine-learning-experiments-adbf27e9d36c/)\n## [Using MLflow To Track Machine Learning Experiments](https://towardsdatascience.com/using-mlflow-to-track-machine-learning-experiments-adbf27e9d36c/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nAn Introduction To MLflow Tracking\n[Ram Vegiraju](https://towardsdatascience.com/author/ram-vegiraju/)\nMarch 22, 20224 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/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  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ \"Productivity Tips, Data Career Insights, and Other Recent Must-Reads\")\n\n\n",
  "metadata": {
    "title": "Linear Discriminant Analysis (LDA) | Towards Data Science",
    "description": "Discover how LDA helps identify critical data features",
    "keywords": null,
    "author": "Ingo Nowitzky",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Linear Discriminant Analysis (LDA)",
    "og:description": "Discover how LDA helps identify critical data features",
    "og:url": "https://towardsdatascience.com/linear-discriminant-analysis-lda-598d8e90f8b9/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/10/12w3EBVnyBuemH0l_mPZfMQ.png",
    "og:image:width": "4135",
    "og:image:height": "1621",
    "og:image:type": "image/png",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Ingo Nowitzky",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "12 min read",
    "article:published_time": "2024-10-12T16:48:27.000Z",
    "article:modified_time": "2024-10-12T16:48:27.000Z",
    "article:author": "https://towardsdatascience.com/author/ingo.nowitzky/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/2581fb17d313/code/block_000.txt",
      "chars": 2818
    },
    {
      "language": "txt",
      "file": "attachments/2581fb17d313/code/block_001.txt",
      "chars": 228
    },
    {
      "language": "txt",
      "file": "attachments/2581fb17d313/code/block_002.txt",
      "chars": 64
    },
    {
      "language": "txt",
      "file": "attachments/2581fb17d313/code/block_003.txt",
      "chars": 167
    },
    {
      "language": "txt",
      "file": "attachments/2581fb17d313/code/block_004.txt",
      "chars": 595
    },
    {
      "language": "txt",
      "file": "attachments/2581fb17d313/code/block_005.txt",
      "chars": 1086
    },
    {
      "language": "txt",
      "file": "attachments/2581fb17d313/code/block_006.txt",
      "chars": 214
    }
  ],
  "images": [
    {
      "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:37:57Z"
    },
    {
      "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:37:57Z"
    },
    {
      "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:37:57Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:37:57Z"
    }
  ],
  "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/artificial-intelligence/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/ingo.nowitzky/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/class-separation/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/data-preparation/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/dimensionality-reduction/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/failure-detection/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/controlling-a-mouse-with-your-eyes-f1097e7cf2e9/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/ryanrudes/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/forecasting-with-granger-causality-checking-for-time-series-spurious-correlations-5faed62c3604/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/cerlymarco/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/facebooks-data-science-interview-practice-problems-46c7263709bf/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/terenceshin/"
    },
    {
      "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://roadmap.sh/machine-learning"
    },
    {
      "type": "external",
      "href": "https://github.com/rasbt/python-machine-learning-book-3rd-edition/blob/master/ch05/images/05_06.png"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=Linear+Discriminant+Analysis+%28LDA%29&u=https%3A%2F%2Ftowardsdatascience.com%2Flinear-discriminant-analysis-lda-598d8e90f8b9%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=Linear+Discriminant+Analysis+%28LDA%29&url=https%3A%2F%2Ftowardsdatascience.com%2Flinear-discriminant-analysis-lda-598d8e90f8b9%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=Linear+Discriminant+Analysis+%28LDA%29&url=https%3A%2F%2Ftowardsdatascience.com%2Flinear-discriminant-analysis-lda-598d8e90f8b9%2F"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/c/TowardsDataScience"
    },
    {
      "type": "external",
      "href": "https://www.threads.net/@towardsdatascience"
    },
    {
      "type": "external",
      "href": "https://bsky.app/profile/towardsdatascience.com"
    },
    {
      "type": "external",
      "href": "https://thenewstack.io"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh"
    },
    {
      "type": "external",
      "href": "https://insightmediagroup.io/creator-network"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:24:00Z",
  "source_url": "https://towardsdatascience.com/linear-discriminant-analysis-lda-598d8e90f8b9/",
  "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[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\n# Linear Discriminant Analysis (LDA)\nDiscover how LDA helps identify critical data features\n[Ingo Nowitzky](https://towardsdatascience.com/author/ingo.nowitzky/)\nOctober 12, 202412 min read\n![Classification of LDA within AI and ML Methods | image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/10/1OQ4qE0xXKDOaRBtBAtNACg.png)\nClassification of LDA within AI and ML Methods | image by author\n**This article aims to explore Linear Discriminant Analysis (LDA), focusing on its core ideas, its mathematical implementation in code, and a practical example from manufacturing. I hope you're on board. Let's get started!**\nWho works with **industrial data** in practice will be familiar with this situation: The datasets usually have many features, and it is often unclear which of the features are important and which are less. \"Important\" is a relative term in this context. Often, the goal is to differentiate the datasets from each other, i.e., to classify them. A very typical task is to distinguish good parts from bad parts and to identify the causes (aka features) that lead to the failure of the parts.\nA commonly used method is the well-known Principal Component Analysis (PCA). While PCA belongs to the **un** supervised methods, the less widespread LDA is a supervised method and thus learns from **labeled data**. Therefore, it is particularly suited for explaining failure patterns from large datasets.\nLearn this step by step with the interactive [Machine Learning](https://roadmap.sh/machine-learning) roadmap.\n## 1. Goal and Principle of LDA\nThe goal of LDA is to linearly combine the features of the data so that the labels of the datasets are best separated from each other, and the number of new features is reduced to a predefined count. In AI jargon, this is typically referred to as a **projection to a lower-dimensional space**.\n![Principle of LDA | image modified from Raschka/Mirjalili, 2019](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/10/1fnaHijTNEzDgVLrnOfsKZQ.png)\nPrinciple of LDA | image modified from [Raschka/Mirjalili, 2019](https://github.com/rasbt/python-machine-learning-book-3rd-edition/blob/master/ch05/images/05_06.png)\n## Excursus: What is dimensionality and what is dimensionality reduction?\n![Dimensions and graphical representation | image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/10/12w3EBVnyBuemH0l_mPZfMQ.png)\nDimensions and graphical representation | image by author\nDimensionality refers to the number of features in a dataset. With just one measurement (or feature), such as the tool temperature from an injection molding machine, we can represent it on a number line. Two features, like temperature and tool pressure, are still manageable: we can easily plot the data on an x-y chart. With three features - temperature, tool pressure, and injection pressure - things get more interesting, but we can still plot the data in a 3D x-y-z chart. However, when we add more features, such as viscosity, electrical conductivity, and others, the complexity increases.\n![Dimensionality reduction | image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/10/1QQFcV9IjsbKzJimlC8UtIg.png)\nDimensionality reduction | image by author\nIn practice, datasets often contain hundreds or even thousands of features. This presents a challenge because many machine learning algorithms perform poorly as datasets grow too large. Additionally, the amount of data required increases exponentially with the number of dimensions to achieve statistical significance. This phenomenon is known as the \"curse of dimensionality.\" These factors make it essential to determine which features are relevant and to eliminate the less meaningful ones early in the data science process.\n## 2. How does LDA work?\nThe process of Linear Discriminant Analysis (LDA) can be broken down into five key steps.\n**Step 1:** Compute the _d_ -dimensional mean vectors for each of the _k_ classes separately from the dataset.\nRemember that LDA is a supervised machine learning technique, meaning we can utilize the known labels. In the first step, we calculate the mean vectors _mean _c_ for all samples belonging to a specific class _c_. To do this, we filter the feature matrix by class label and compute the mean for each of the _d_ features. As a result, we obtain _k_ mean vectors (one for each of the _k_ classes), each with a length of _d_ (corresponding to the _d_ features).\n![Label vector Y and feature matrix X | image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/10/1N-VbzV-PotaEJ7nwK6oSIQ.png)\nLabel vector Y and feature matrix X | image by author\n**Step 2:** Compute the scatter matrices (between-class scatter matrix and within-class scatter matrix).\nThe within-class scatter matrix measures the variation among samples within the same class. To find a subspace with optimal separability, we aim to minimize the values in this matrix. In contrast, the between-class scatter matrix measures the variation between different classes. For optimal separability, we aim to maximize the values in this matrix. Intuitively, within-class scatter looks at how compact each class is, whereas between-class scatter examines how far apart different classes are.\n![Within-class and between-class scatter matrices | image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/10/10fCEtLfTJPYrjcJ5ihaFOQ.png)\nWithin-class and between-class scatter matrices | image by author\nLet's start with the **within-class scatter** matrix _S _W_. It is calculated as the sum of the scatter matrices _S _c_ for each individual class:\nThe **between-class scatter** matrix _S _B_ is derived from the differences between the class means _mean _c_ and the overall mean of the entire dataset:\nwhere _mean_ refers to the mean vector calculated over all samples, regardless of their class labels.\n**Step 3:** Calculate the eigenvectors and eigenvalues for the ratio of _S _W_ ​ and _S _B_ ​.\nAs mentioned, for optimal class separability, we aim to maximize _S _B​_ and minimize _S _W_ ​. We can achieve both by maximizing the ratio _S_B/S _W_ ​. In linear algebra terms, this ratio corresponds to the scatter matrix _S_W⁻¹ S _B_ ​, which is maximized in the subspace spanned by the eigenvectors with the highest eigenvalues. The eigenvectors define the directions of this subspace, while the eigenvalues represent the magnitude of the distortion. We will select the _m_ eigenvectors associated with the highest eigenvalues.\n![Subspace spanned by eigenvectors | image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/10/1gxwb2V5kGl2tg-mXITN29A.png)\nSubspace spanned by eigenvectors | image by author\n**Step 4:** Sort the eigenvectors in descending order of their corresponding eigenvalues, and select the _m_ eigenvectors with the largest eigenvalues to form a _d × m-_dimensional transformation matrix _W_.\nRemember, our goal is not only to project the data into a subspace that enhances class separability but also to reduce dimensionality. The eigenvectors will define the axes of our new feature subspace. To decide which eigenvectors to discard for the lower-dimensional subspace, we need to examine their corresponding eigenvalues. In simple terms, the eigenvectors with the smallest eigenvalues contribute the least to class separation, and these are the ones we want to drop. The typical approach is to rank the eigenvalues in descending order and select the top _m_ eigenvectors. _m_ is a freely chosen parameter. The larger _m_ , the less information is lost during the transformation.\nAfter sorting the eigenpairs by decreasing eigenvalues and selecting the top _m_ pairs, the next step is to construct the _d × m_ -dimensional transformation matrix _W_. This is done by stacking the _m_ selected eigenvectors horizontally, resulting in the matrix _W_ :\nThe first column of _W_ represents the eigenvector corresponding to the highest eigenvalue, the second column represents the eigenvector corresponding to the second highest eigenvalue, and so on.\n**Step 5:** Use _W_ to project the samples onto the new subspace.\nIn the final step, we use the _d × m-_dimensional transformation matrix _W_ , which we composed from the top _m_ selected eigenvectors, to project our samples onto the new subspace:\nwhere _X_ is the initial _n × d_ -dimensional feature matrix representing our samples, and _Z_ is the newly transformed _n × m_ -dimensional feature matrix in the new subspace. This means that the selected eigenvectors serve as the \"recipes\" for transforming the original features into the new features (the **Linear Discriminants**): The eigenvector with the highest eigenvalue provides the transformation recipe for **LD1** , the eigenvector with the second highest eigenvalue corresponds to **LD2** , and so on.\n![Projection of X onto the linear discriminants LD](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/10/1x_DupdGQKwHFvpsAaA950A.png)\nProjection of X onto the linear discriminants LD\n## 3. Implementing Linear Discriminant Analysis (LDA) from Scratch\nTo demonstrate the theory and mathematics in action, we will program our own LDA from scratch using only numpy.\npython\n\n```\nimport numpy as np\n\nclass LDA_fs:\n    \"\"\"\n    Performs a Linear Discriminant Analysis (LDA)\n\n    Methods\n    =======\n    fit_transform():\n        Fits the model to the data X and Y, derives the transformation matrix W\n    and projects the feature matrix X onto the m LDA axes\n    \"\"\"\n\n    def __init__(self, m):\n        \"\"\"\n        Parameters\n        ==========\n        m : int\n            Number of LDA axes onto which the data will be projected\n\n        Returns\n        =======\n        None\n        \"\"\"\n        self.m = m\n\n    def fit_transform(self, X, Y):\n        \"\"\"\n        Parameters\n        ==========\n        X : array(n_samples, n_features)\n            Feature matrix of the dataset\n        Y = array(n_samples)\n            Label vector of the dataset\n\n        Returns\n        =======\n        X_transform : New feature matrix projected onto the m LDA axes\n\n        \"\"\"\n\n        # Get number of features (columns)\n        self.n_features = X.shape[1]\n        # Get unique class labels\n        class_labels = np.unique(Y)\n        # Get the overall mean vector (independent of the class labels)\n        mean_overall = np.mean(X, axis=0)  # Mean of each feature\n        # Initialize both scatter matrices with zeros\n        SW = np.zeros((self.n_features, self.n_features))  # Within scatter matrix\n        SB = np.zeros((self.n_features, self.n_features))  # Between scatter matrix\n\n        # Iterate over all classes and select the corresponding data\n        for c in class_labels:\n            # Filter X for class c\n            X_c = X[Y == c]\n            # Calculate the mean vector for class c\n            mean_c = np.mean(X_c, axis=0)\n            # Calculate within-class scatter for class c\n            SW += (X_c - mean_c).T.dot((X_c - mean_c))\n            # Number of samples in class c\n            n_c = X_c.shape[0]\n            # Difference between the overall mean and the mean of class c --> between-class scatter\n            mean_diff = (mean_c - mean_overall).reshape(self.n_features, 1)\n            SB += n_c * (mean_diff).dot(mean_diff.T)\n\n        # Determine SW^-1 * SB\n        A = np.linalg.inv(SW).dot(SB)\n        # Get the eigenvalues and eigenvectors of (SW^-1 * SB)\n        eigenvalues, eigenvectors = np.linalg.eig(A)\n        # Keep only the real parts of eigenvalues and eigenvectors\n        eigenvalues = np.real(eigenvalues)\n        eigenvectors = np.real(eigenvectors.T)\n\n        # Sort the eigenvalues descending (high to low)\n        idxs = np.argsort(np.abs(eigenvalues))[::-1]\n        self.eigenvalues = np.abs(eigenvalues[idxs])\n        self.eigenvectors = eigenvectors[idxs]\n        # Store the first m eigenvectors as transformation matrix W\n        self.W = self.eigenvectors[0:self.m]\n\n        # Transform the feature matrix X onto LD axes\n        return np.dot(X, self.W.T)\n```\n\n## 4. Applying LDA to an Industrial Dataset\nTo see LDA in action, we will apply it to a typical task in the production environment. We have data from a simple manufacturing line with only 7 stations. Each of these stations sends a data point (yes, I know, only one data point is highly unrealistic). Unfortunately, our line produces a significant number of defective parts, and we want to find out which stations are responsible for this.\nFirst, we load the data and take an initial look.\npython\n\n```\nimport pandas as pd\n\n# URL to Github repository\nurl = \"https://raw.githubusercontent.com/IngoNowitzky/LDA_Medium/main/production_line_data.csv\"\n\n# Read csv to DataFrame\ndata = pd.read_csv(url)\n\n# Print first 5 lines\ndata.head()\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/10/1IHl_-rYCyoBpgbov9ZXiAQ.png)\nNext, we study the distribution of the data using the `.describe()` method from Pandas.\npython\n\n```\n# Show average, min and max of numerical values\ndata.describe()\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/10/1bp5HoeXSwbekKjWXdralgw.png)\nWe see that we have 20,000 data points, and the measurements range from -5 to +150. Hence, we note for later that we need to normalize the dataset: the different magnitudes of the numerical values would otherwise negatively affect the LDA. How many good parts and how many bad parts do we have?\npython\n\n```\n# Count the number of good and bad parts\nlabel_counts = data['Label'].value_counts()\n\n# Display the results\nprint(\"Number of Good and Bad Parts:\")\nprint(label_counts)\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/10/1CNw-Ue_g8Q_FsJPOZ4iIrw.png)\nWe have 19,031 good parts and 969 defective parts. The fact that the dataset is so imbalanced is an issue for further analysis. Therefore, we select all defective parts and an equal number of randomly chosen good parts for the further processing.\npython\n\n```\n# Select all bad parts\nbad_parts = data[data['Label'] == 'Bad']\n\n# Randomly select an equal number of good parts\ngood_parts = data[data['Label'] == 'Good'].sample(n=len(bad_parts), random_state=42)\n\n# Combine both subsets to create a balanced dataset\nbalanced_data = pd.concat([bad_parts, good_parts])\n\n# Shuffle the combined dataset\nbalanced_data = balanced_data.sample(frac=1, random_state=42).reset_index(drop=True)\n\n# Display the number of good and bad parts in the balanced dataset\nprint(\"Number of Good and Bad Parts in the balanced dataset:\")\nprint(balanced_data['Label'].value_counts())\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/10/1L_SVv2hkWxY_SM4F6J2F1w.png)\nNow, let's apply our LDA from scratch to the balanced dataset. We use the `StandardScaler` from `sklearn` to normalize the measurements for each feature to have a mean of 0 and a standard deviation of 1. We choose only one linear discriminant axis (_m=1_) onto which we project the data. This helps us clearly see which features are most relevant in distinguishing good from bad parts, and we visualize the projected data in a histogram.\npython\n\n```\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler\n\n# Separate features and labels\nX = balanced_data.drop(columns=['Label'])\ny = balanced_data['Label']\n\n# Normalize the features\nscaler = StandardScaler()\nX_scaled = scaler.fit_transform(X)\n\n# Perform LDA\nlda = LDA_fs(m=1)  # Instanciate LDA object with 1 axis\nX_lda = lda.fit_transform(X_scaled, y) # Fit the model and project the data\n\n# Plot the LDA projection\nplt.figure(figsize=(10, 6))\nplt.hist(X_lda[y == 'Good'], bins=20, alpha=0.7, label='Good', color='green')\nplt.hist(X_lda[y == 'Bad'], bins=20, alpha=0.7, label='Bad', color='red')\nplt.title(\"LDA Projection of Good and Bad Parts\")\nplt.xlabel(\"LDA Component\")\nplt.ylabel(\"Frequency\")\nplt.legend()\nplt.show()\n\n# Examine feature contributions to the LDA component\nfeature_importance = pd.DataFrame({'Feature': X.columns, 'LDA Coefficient': lda.W[0]})\nfeature_importance = feature_importance.sort_values(by='LDA Coefficient', ascending=False)\n\n# Display feature importance\nprint(\"Feature Contributions to LDA Component:\")\nprint(feature_importance)\n```\n\n![Feature matrix projected to one LD \\(m=1\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/10/1mXrC3tBxEQMZxmY4uFqOlg.png)\nFeature matrix projected to one LD (m=1)\n![Feature importance = How much do the stations contribute to class separation?](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/10/1tXg8b0JFGIb5FrXx6MRV7A.png)\nFeature importance = How much do the stations contribute to class separation?\nThe histogram shows that we can separate the good parts from the defective parts very well, with only a small overlap. This is already a positive result and indicates that our LDA was successful.\nThe \"LDA Coefficients\" from the table \"Feature Contributions to LDA Components\" represent the eigenvector from the first (and only, since _m=1_) column of our transformation matrix _W_. They indicate the direction and magnitude with which the normalized measurements from the stations are projected onto the linear discriminant axis. The values in the table are sorted in descending order. We need to read the table from both the top and the bottom simultaneously because the absolute value of the coefficient indicates the significance of each station in separating the classes and, consequently, its contribution to the production of defective parts. The sign indicates whether a lower or higher measurement increases the likelihood of defective parts. Let's take a closer look at our example:\nThe largest absolute value is from Station 4, with a coefficient of -0.672. This means that Station 4 has the strongest influence on part failure. Due to the negative sign, higher positive measurements are projected towards a negative linear discriminant (LD). The histogram shows that a negative LD is associated with good (green) parts. Conversely, **low and negative measurements at this station increase the likelihood of part failure**. The second highest absolute value is from Station 2, with a coefficient of 0.557. Therefore, this station is the second most significant contributor to part failures. The positive sign indicates that high positive measurements are projected towards the positive LD. From the histogram, we know that a high positive LD value is associated with a high likelihood of failure. In other words, **high measurements at Station 2 lead to part failures**. The third highest coefficient comes from Station 7, with a value of -0.486. This makes Station 7 the third largest contributor to part failures. The negative sign again indicates that high positive values at this station lead to a negative LD (which corresponds to good parts). Conversely, **low and negative values at this station lead to part failures**. All other LDA coefficients are an order of magnitude smaller than the three mentioned, **the associated stations therefore have no influence on part failure**.\nAre the results of our LDA analysis correct? As you may have already guessed, the production dataset is synthetically generated. I labeled all parts as defective where the measurement at Station 2 was greater than 0.5, the value at Station 4 was less than -2.5, and the value at Station 7 was less than 3. **It turns out that the LDA hit the mark perfectly!**\npython\n\n```\n# Determine if a sample is a good or bad part based on the conditions\ndata['Label'] = np.where(\n    (data['Station_2'] > 0.5) &amp; (data['Station_4'] < -2.5) &amp; (data['Station_7'] < 3),\n    'Bad',\n    'Good'\n)\n```\n\n## 5. Conclusion\nLinear Discriminant Analysis (LDA) not only reduces the complexity of datasets but also highlights the key features that drive class separation, making it highly effective for identifying failure causes in production systems. It is a straightforward yet powerful method with practical applications and is readily available in libraries like `scikit-learn`.\nTo achieve optimal results, it is crucial to balance the dataset (ensure a similar number of samples in each class) and normalize it (mean of 0 and standard deviation of 1). **The next time you work with a large dataset containing class labels and numerous features, why not give LDA a try?**\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/1787657681444_t7ljpr.jpeg)\nWritten By\n## [Ingo Nowitzky](https://towardsdatascience.com/author/ingo.nowitzky/)\nPhD Engineer, Lean Production professional, and AI enthisiast.\n[See all from Ingo Nowitzky](https://towardsdatascience.com/author/ingo.nowitzky/)\n[class-separation](https://towardsdatascience.com/tag/class-separation/)[Data Preparation](https://towardsdatascience.com/tag/data-preparation/)[Dimensionality Reduction](https://towardsdatascience.com/tag/dimensionality-reduction/)[Failure Detection](https://towardsdatascience.com/tag/failure-detection/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Flinear-discriminant-analysis-lda-598d8e90f8b9%2F&title=Linear%20Discriminant%20Analysis%20\\(LDA\\))\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Flinear-discriminant-analysis-lda-598d8e90f8b9%2F&title=Linear%20Discriminant%20Analysis%20\\(LDA\\))\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Flinear-discriminant-analysis-lda-598d8e90f8b9%2F&text=Linear%20Discriminant%20Analysis%20\\(LDA\\))\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/2020/09/115ZuFhSoN1JLG5zWJCf73g.png)](https://towardsdatascience.com/controlling-a-mouse-with-your-eyes-f1097e7cf2e9/)\n## [Controlling a Mouse With Your Eyes](https://towardsdatascience.com/controlling-a-mouse-with-your-eyes-f1097e7cf2e9/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA Machine Learning approach to eye pose estimation from just a single front-facing perspective as input.\n[Ryan Rudes](https://towardsdatascience.com/author/ryanrudes/)\nSeptember 21, 20207 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/0V_YP1jpqoye93A7k-scaled.jpg)](https://towardsdatascience.com/forecasting-with-granger-causality-checking-for-time-series-spurious-correlations-5faed62c3604/)\n## [Forecasting with Granger Causality: Checking for Time Series Spurious Correlations](https://towardsdatascience.com/forecasting-with-granger-causality-checking-for-time-series-spurious-correlations-5faed62c3604/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nHacking Granger Causality Test with ML Approaches\n[Marco Cerliani](https://towardsdatascience.com/author/cerlymarco/)\nApril 6, 20235 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/03/1MzSvz7CBKCN4XUgQ0A7ybA.png)](https://towardsdatascience.com/facebooks-data-science-interview-practice-problems-46c7263709bf/)\n## [Facebook's Data Science Interview Practice Problems](https://towardsdatascience.com/facebooks-data-science-interview-practice-problems-46c7263709bf/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA walkthrough of some of Facebook's interview questions!\n[Terence Shin, MSc, MBA](https://towardsdatascience.com/author/terenceshin/)\nMarch 8, 20208 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/10/0UuWQSZLhG7BvlXjq-scaled.jpg)](https://towardsdatascience.com/why-gradient-descent-works-4e487d3c84c1/)\n## [Why Gradient Descent Works?](https://towardsdatascience.com/why-gradient-descent-works-4e487d3c84c1/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nEverybody knows what Gradient Descent is and how it works. Ever wondered why it works? Here's a mathematical explanation\n[Kunj Mehta](https://towardsdatascience.com/author/kunjmehta10/)\nOctober 20, 20214 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1q0SQTHMQGVHSIYJ7Kl6W5A.jpeg)](https://towardsdatascience.com/putting-your-models-into-production-5ae3191722b9/)\n## [Putting Your Models Into Production](https://towardsdatascience.com/putting-your-models-into-production-5ae3191722b9/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nA guide to getting your deep learning model into production with TensorFlow Serving.\n[Zito Relova](https://towardsdatascience.com/author/zito-relova/)\nApril 13, 20214 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/02/1UOqItmSOFQGS3JwL-R2wHQ.png)](https://towardsdatascience.com/why-is-cross-entropy-equal-to-kl-divergence-d4d2ec413864/)\n## [Why Is Cross Entropy Equal to KL-Divergence?](https://towardsdatascience.com/why-is-cross-entropy-equal-to-kl-divergence-d4d2ec413864/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nIt is a common practice to use cross-entropy in the loss function while constructing a Generative Adversarial Network [1] even though...\n[J. Rafid Siddiqui, PhD](https://towardsdatascience.com/author/azad-wolf/)\nFebruary 6, 20223 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/03/image-252.png)](https://towardsdatascience.com/the-math-thats-killing-your-ai-agent/)\n## [The Math That’s Killing Your AI Agent](https://towardsdatascience.com/the-math-thats-killing-your-ai-agent/)\n[Agentic AI](https://towardsdatascience.com/category/artificial-intelligence/agentic-ai/)\nAn 85% accurate agent fails four out of five times on a 10-step task. Here's the arithmetic nobody runs before deploying.\n[Kaushik Rajan](https://towardsdatascience.com/author/kaushikvr06/)\nMarch 20, 202611 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/09/1zNQsCy3AxqME_UX7eR4lYQ.png)](https://towardsdatascience.com/from-research-to-production-with-deep-semi-supervised-learning-7caaedc39093/)\n## [From Research to Production with Deep Semi-Supervised Learning](https://towardsdatascience.com/from-research-to-production-with-deep-semi-supervised-learning-7caaedc39093/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nSemi-Supervised Learning (SSL) has blossomed in the deep learning research community - we share lessons learned taking SSL into production.\n[Varun Nair](https://towardsdatascience.com/author/nairvarun/)\nSeptember 25, 202016 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/03/0T69MzDADVxfcePc0.jpg)](https://towardsdatascience.com/using-mlflow-to-track-machine-learning-experiments-adbf27e9d36c/)\n## [Using MLflow To Track Machine Learning Experiments](https://towardsdatascience.com/using-mlflow-to-track-machine-learning-experiments-adbf27e9d36c/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nAn Introduction To MLflow Tracking\n[Ram Vegiraju](https://towardsdatascience.com/author/ram-vegiraju/)\nMarch 22, 20224 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/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  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ \"Productivity Tips, Data Career Insights, and Other Recent Must-Reads\")\n\n\n",
  "body_base_path": "attachments/2581fb17d313/pages/",
  "body_markdown_path": "attachments/2581fb17d313/pages/archived-body.md",
  "local_html": "attachments/2581fb17d313/pages/archived-body.html",
  "body_source": "prior_capture"
}