{"id":855,"date":"2024-12-28T07:03:39","date_gmt":"2024-12-28T07:03:39","guid":{"rendered":"https:\/\/mailitics.com\/index.php\/2024\/12\/28\/introduction-to-the-finite-normal-mixtures-in-regression-with-6a884810a692\/"},"modified":"2024-12-28T07:03:39","modified_gmt":"2024-12-28T07:03:39","slug":"introduction-to-the-finite-normal-mixtures-in-regression-with-6a884810a692","status":"publish","type":"post","link":"https:\/\/mailitics.com\/index.php\/2024\/12\/28\/introduction-to-the-finite-normal-mixtures-in-regression-with-6a884810a692\/","title":{"rendered":"Introduction to the Finite Normal Mixtures in Regression with"},"content":{"rendered":"<p>    Introduction to the Finite Normal Mixtures in Regression with<br \/>\n \t<BR><br \/>\n<BR><\/BR><br \/>\n    <!-- no image --><br \/>\n \t<BR><br \/>\n<BR><\/BR><\/p>\n<div>\n<h3>Introduction to the Finite Normal Mixtures in Regression with\u00a0R<\/h3>\n<h4>How to make linear regression flexible enough for non-linear data<\/h4>\n<p>The linear regression is usually considered not flexible enough to tackle the nonlinear data. From theoretical viewpoint it is not capable to dealing with them. However, we can make it work for us with any dataset by using finite normal mixtures in a regression model. This way it becomes a very powerful machine learning tool which can be applied to virtually any dataset, even highly non-normal with non-linear dependencies across the variables.<\/p>\n<p>What makes this approach particularly interesting comes with interpretability. Despite an extremely high level of flexibility all the detected relations can be directly interpreted. The model is as general as neural network, still it does not become a black-box. You can read the relations and understand the impact of individual variables.<\/p>\n<p>In this post, we demonstrate how to simulate a finite mixture model for regression using Markov Chain Monte Carlo (MCMC) sampling. We will generate data with multiple components (groups) and fit a mixture model to recover these components using Bayesian inference. This process involves regression models and mixture models, combining them with MCMC techniques for parameter estimation.<\/p>\n<figure><img data-recalc-dims=\"1\" decoding=\"async\" alt=\"\" src=\"https:\/\/i0.wp.com\/cdn-images-1.medium.com\/max\/655\/1%2AbB37tG2PcuEy2rbaQlFUDw.png?ssl=1\"><figcaption>Data simulated as a mixtures of three linear regressions<\/figcaption><\/figure>\n<h3>Loading Required Libraries<\/h3>\n<p>We begin by loading the necessary libraries to work with regression models, MCMC, and multivariate distributions<\/p>\n<pre># Loading the required libraries for various functions<br>library(\"pscl\")         # For pscl specific functions, like regression models<br>library(\"MCMCpack\")     # For MCMC sampling functions, including posterior distributions<br>library(mvtnorm)        # For multivariate normal distribution functio<\/pre>\n<ul>\n<li>\n<strong>pscl<\/strong>: Used for various statistical functions like regression models.<\/li>\n<li>\n<strong>MCMCpack<\/strong>: Contains functions for Bayesian inference, particularly MCMC sampling.<\/li>\n<li>\n<strong>mvtnorm<\/strong>: Provides tools for working with multivariate normal distributions.<\/li>\n<\/ul>\n<h3>Data Generation<\/h3>\n<p>We simulate a dataset where each observation belongs to one of several groups (components of the mixture model), and the response variable is generated using a regression model with random coefficients.<\/p>\n<p>We consider a general setup for a regression model using G Normal mixture components.<\/p>\n<figure><img data-recalc-dims=\"1\" decoding=\"async\" alt=\"\" src=\"https:\/\/i0.wp.com\/cdn-images-1.medium.com\/max\/676\/1%2A7EQtGxYfanML9eWZ4j4LsQ.png?ssl=1\"><\/figure>\n<pre>## Generate the observations<br># Set the length of the time series (number of observations per group)<br>N &lt;- 1000<br># Set the number of simulations (iterations of the MCMC process)<br>nSim &lt;- 200<br># Set the number of components in the mixture model (G is the number of groups)<br>G &lt;- 3<\/pre>\n<ul>\n<li>\n<strong>N<\/strong>: The number of observations per\u00a0group.<\/li>\n<li>\n<strong>nSim<\/strong>: The number of MCMC iterations.<\/li>\n<li>\n<strong>G<\/strong>: The number of components (groups) in our mixture\u00a0model.<\/li>\n<\/ul>\n<h4>Simulating Data<\/h4>\n<p>Each group is modeled using a univariate regression model, where the explanatory variables (X) and the response variable (y) are simulated from normal distributions. The betas represent the regression coefficients for each group, and sigmas represent the variance for each\u00a0group.<\/p>\n<pre># Set the values for the regression coefficients (betas) for each group<br>betas &lt;- 1:sum(dimG) * 2.5  # Generating sequential betas with a multiplier of 2.5<br># Define the variance (sigma) for each component (group) in the mixture<br>sigmas &lt;- rep(1, G) \/ 1  # Set variance to 1 for each component, with a fixed divisor of 1<\/pre>\n<ul>\n<li>\n<strong>betas<\/strong>: These are the regression coefficients. Each group\u2019s coefficient is sequentially assigned.<\/li>\n<li>\n<strong>sigmas<\/strong>: Represents the variance for each group in the mixture\u00a0model.<\/li>\n<\/ul>\n<p>In this model we allow each mixture component to possess its own variance paraameter and set of regression parameters.<\/p>\n<h4>Group Assignment and\u00a0Mixing<\/h4>\n<p>We then simulate the group assignment of each observation using a random assignment and mix the data for all components.<\/p>\n<p>We augment the model with a set of component label vectors\u00a0for<\/p>\n<figure><img data-recalc-dims=\"1\" decoding=\"async\" alt=\"\" src=\"https:\/\/i0.wp.com\/cdn-images-1.medium.com\/max\/80\/1%2A0JeagbrBM-cEooxcNku9Kw.png?ssl=1\"><\/figure>\n<p>where<\/p>\n<figure><img data-recalc-dims=\"1\" decoding=\"async\" alt=\"\" src=\"https:\/\/i0.wp.com\/cdn-images-1.medium.com\/max\/231\/1%2ANElEwXWC0AE58dLWM1z_-A.png?ssl=1\"><\/figure>\n<p>and thus <em>z_gi=1<\/em> implies that the <em>i-<\/em>th individual is drawn from the <em>g-<\/em>th component of the\u00a0mixture.<\/p>\n<p>This random assignment forms the z_original vector, representing the true group each observation belongs\u00a0to.<\/p>\n<pre># Initialize the original group assignments (z_original)<br>z_original &lt;- matrix(NA, N * G, 1)<br># Repeat each group label N times (assign labels to each observation per group)<br>z_original &lt;- rep(1:G, rep(N, G))<br># Resample the data rows by random order<br>sampled_order &lt;- sample(nrow(data))<br># Apply the resampled order to the data<br>data &lt;- data[sampled_order,]<\/pre>\n<h3>Bayesian Inference: Priors and Initialization<\/h3>\n<p>We set prior distributions for the regression coefficients and variances. These priors will guide our Bayesian estimation.<\/p>\n<figure><img data-recalc-dims=\"1\" decoding=\"async\" alt=\"\" src=\"https:\/\/i0.wp.com\/cdn-images-1.medium.com\/max\/420\/1%2A-QyRfZLqC4iFSNIvRZRMRQ.png?ssl=1\"><\/figure>\n<pre>## Define Priors for Bayesian estimation# Define the prior mean (muBeta) for the regression coefficients<br>muBeta &lt;- matrix(0, G, 1)# Define the prior variance (VBeta) for the regression coefficients<br>VBeta &lt;- 100 * diag(G)  # Large variance (100) as a prior for the beta coefficients# Prior for the sigma parameters (variance of each component)<br>ag &lt;- 3  # Shape parameter<br>bg &lt;- 1\/2  # Rate parameter for the prior on sigma<br>shSigma &lt;- ag<br>raSigma &lt;- bg^(-1)<\/pre>\n<ul>\n<li>\n<strong>muBeta<\/strong>: The prior mean for the regression coefficients. We set it to 0 for all components.<\/li>\n<li>\n<strong>VBeta<\/strong>: The prior variance, which is large (100) to allow flexibility in the coefficients.<\/li>\n<li>\n<strong>shSigma<\/strong> and <strong>raSigma<\/strong>: Shape and rate parameters for the prior on the variance (sigma) of each\u00a0group.<\/li>\n<\/ul>\n<p>For the component indicators and component probabilities we consider following prior assignment<\/p>\n<figure><img data-recalc-dims=\"1\" decoding=\"async\" alt=\"\" src=\"https:\/\/i0.wp.com\/cdn-images-1.medium.com\/max\/658\/1%2ADKuTxxVTX7PCGpRQeOHS7w.png?ssl=1\"><\/figure>\n<p>The multinomial prior M is the multivariate generalizations of the binomial, and the Dirichlet prior D is a multivariate generalization of the beta distribution.<\/p>\n<h3>MCMC Initialization<\/h3>\n<p>In this section, we initialize the MCMC process by setting up matrices to store the samples of the regression coefficients, variances, and mixing proportions.<\/p>\n<pre>## Initialize MCMC sampling# Initialize matrix to store the samples for beta<br>mBeta &lt;- matrix(NA, nSim, G)# Assign the first value of beta using a random normal distribution<br>for (g in 1:G) {<br>  mBeta[1, g] &lt;- rnorm(1, muBeta[g, 1], VBeta[g, g])<br>}# Initialize the sigma^2 values (variance for each component)<br>mSigma2 &lt;- matrix(NA, nSim, G)<br>mSigma2[1, ] &lt;- rigamma(1, shSigma, raSigma)# Initialize the mixing proportions (pi), using a Dirichlet distribution<br>mPi &lt;- matrix(NA, nSim, G)<br>alphaPrior &lt;- rep(N\/G, G)  # Prior for the mixing proportions, uniform across groups<br>mPi[1, ] &lt;- rdirichlet(1, alphaPrior)<\/pre>\n<ul>\n<li>\n<strong>mBeta<\/strong>: Matrix to store samples of the regression coefficients.<\/li>\n<li>\n<strong>mSigma2<\/strong>: Matrix to store the variances (sigma squared) for each component.<\/li>\n<li>\n<strong>mPi<\/strong>: Matrix to store the mixing proportions, initialized using a Dirichlet distribution.<\/li>\n<\/ul>\n<h3>MCMC Sampling: Posterior Updates<\/h3>\n<p>If we condition on the values of the component indicator variables z, the conditional likelihood can be expressed as<\/p>\n<figure><img data-recalc-dims=\"1\" decoding=\"async\" alt=\"\" src=\"https:\/\/i0.wp.com\/cdn-images-1.medium.com\/max\/761\/1%2AXr6VteCFT0FvL-J9EDj--Q.png?ssl=1\"><\/figure>\n<p>In the MCMC sampling loop, we update the group assignments (z), regression coefficients (beta), and variances (sigma) based on the posterior distributions. The likelihood of each group assignment is calculated, and the group with the highest posterior probability is selected.<\/p>\n<p>The following complete posterior conditionals can be obtained:<\/p>\n<figure><img data-recalc-dims=\"1\" decoding=\"async\" alt=\"\" src=\"https:\/\/i0.wp.com\/cdn-images-1.medium.com\/max\/538\/1%2A7h9QN0edlWOkMQOcji1dAA.png?ssl=1\"><\/figure>\n<p>where<\/p>\n<figure><img data-recalc-dims=\"1\" decoding=\"async\" alt=\"\" src=\"https:\/\/i0.wp.com\/cdn-images-1.medium.com\/max\/46\/1%2AFw6jVVJd4hGiTFY25yO7wA.png?ssl=1\"><\/figure>\n<p>denotes all the parameters in our posterior other than\u00a0<em>x<\/em>.<\/p>\n<figure><img data-recalc-dims=\"1\" decoding=\"async\" alt=\"\" src=\"https:\/\/i0.wp.com\/cdn-images-1.medium.com\/max\/928\/1%2Aq5BR0NhR6DD6Yc8p5QbOIg.png?ssl=1\"><\/figure>\n<p>and where <em>n_g<\/em> denotes the number of observations in the <em>g<\/em>-th component of the\u00a0mixture.<\/p>\n<figure><img data-recalc-dims=\"1\" decoding=\"async\" alt=\"\" src=\"https:\/\/i0.wp.com\/cdn-images-1.medium.com\/max\/740\/1%2AGf48ETMXywEmQ8nu4khbLw.png?ssl=1\"><\/figure>\n<p>and<\/p>\n<figure><img data-recalc-dims=\"1\" decoding=\"async\" alt=\"\" src=\"https:\/\/i0.wp.com\/cdn-images-1.medium.com\/max\/539\/1%2A0HFE_qvUgmZeCc3E-isL9g.png?ssl=1\"><\/figure>\n<p>Algorithm below draws from the series of posterior distributions above in a sequential order.<\/p>\n<pre>## Start the MCMC iterations for posterior sampling# Loop over the number of simulations<br>for (i in 2:nSim) {<br>  print(i)  # Print the current iteration number<br>  <br>  # For each observation, update the group assignment (z)<br>  for (t in 1:(N*G)) {<br>    fig &lt;- NULL<br>    for (g in 1:G) {<br>      # Calculate the likelihood of each group and the corresponding posterior probability<br>      fig[g] &lt;- dnorm(y[t, 1], X[t, ] %*% mBeta[i-1, g], sqrt(mSigma2[i-1, g])) * mPi[i-1, g]<br>    }<br>    # Avoid zero likelihood and adjust it<br>    if (all(fig) == 0) {<br>      fig &lt;- fig + 1\/G<br>    }<br>    <br>    # Sample a new group assignment based on the posterior probabilities<br>    z[i, t] &lt;- which(rmultinom(1, 1, fig\/sum(fig)) == 1)<br>  }<br>  <br>  # Update the regression coefficients for each group<br>  for (g in 1:G) {<br>    # Compute the posterior mean and variance for beta (using the data for group g)<br>    DBeta &lt;- solve(t(X[z[i, ] == g, ]) %*% X[z[i, ] == g, ] \/ mSigma2[i-1, g] + solve(VBeta[g, g]))<br>    dBeta &lt;- t(X[z[i, ] == g, ]) %*% y[z[i, ] == g, 1] \/ mSigma2[i-1, g] + solve(VBeta[g, g]) %*% muBeta[g, 1]<br>    <br>    # Sample a new value for beta from the multivariate normal distribution<br>    mBeta[i, g] &lt;- rmvnorm(1, DBeta %*% dBeta, DBeta)<br>    <br>    # Update the number of observations in group g<br>    ng[i, g] &lt;- sum(z[i, ] == g)<br>    <br>    # Update the variance (sigma^2) for each group<br>    mSigma2[i, g] &lt;- rigamma(1, ng[i, g]\/2 + shSigma, raSigma + 1\/2 * sum((y[z[i, ] == g, 1] - (X[z[i, ] == g, ] * mBeta[i, g]))^2))<br>  }<br>  <br>  # Reorder the group labels to maintain consistency<br>  reorderWay &lt;- order(mBeta[i, ])<br>  mBeta[i, ] &lt;- mBeta[i, reorderWay]<br>  ng[i, ] &lt;- ng[i, reorderWay]<br>  mSigma2[i, ] &lt;- mSigma2[i, reorderWay]<br>  <br>  # Update the mixing proportions (pi) based on the number of observations in each group<br>  mPi[i, ] &lt;- rdirichlet(1, alphaPrior + ng[i, ])<br>}<\/pre>\n<p>This block of code performs the key steps in\u00a0MCMC:<\/p>\n<ul>\n<li>\n<strong>Group Assignment Update<\/strong>: For each observation, we calculate the likelihood of the data belonging to each group and update the group assignment accordingly.<\/li>\n<li>\n<strong>Regression Coefficient Update<\/strong>: The regression coefficients for each group are updated using the posterior mean and variance, which are calculated based on the observed\u00a0data.<\/li>\n<li>\n<strong>Variance Update<\/strong>: The variance of the response variable for each group is updated using the inverse gamma distribution.<\/li>\n<\/ul>\n<h3>Visualizing the\u00a0Results<\/h3>\n<p>Finally, we visualize the results of the MCMC sampling. We plot the posterior distributions for each regression coefficient, compare them to the true values, and plot the most likely group assignments.<\/p>\n<pre># Plot the posterior distributions for each beta coefficient<br>par(mfrow=c(G,1))<br>for (g in 1:G) {<br>  plot(density(mBeta[5:nSim, g]), main = 'True parameter (vertical) and the distribution of the samples')  # Plot the density for the beta estimates<br>  abline(v = betas[g])  # Add a vertical line at the true value of beta for comparison<br>}<\/pre>\n<p>This plot shows how the MCMC samples (posterior distribution) for the regression coefficients converge to the true values\u00a0(betas).<\/p>\n<h3>Conclusion<\/h3>\n<p>Through this process, we demonstrated how finite normal mixtures can be used in a regression context, combined with MCMC for parameter estimation. By simulating data with known groupings and recovering the parameters through Bayesian inference, we can assess how well our model captures the underlying structure of the\u00a0data.<\/p>\n<p><iframe loading=\"lazy\" src=\"\" width=\"0\" height=\"0\" frameborder=\"0\" scrolling=\"no\"><a href=\"https:\/\/medium.com\/media\/4486014471a1008d7b7e9c2908e0b793\/href\">https:\/\/medium.com\/media\/4486014471a1008d7b7e9c2908e0b793\/href<\/a><\/iframe><\/p>\n<p><em>Unless otherwise noted, all images are by the\u00a0author.<\/em><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/medium.com\/_\/stat?event=post.clientViewed&amp;referrerSource=full_rss&amp;postId=6a884810a692\" width=\"1\" height=\"1\" alt=\"\"><\/p>\n<hr>\n<p><a href=\"https:\/\/towardsdatascience.com\/introduction-to-the-finite-normal-mixtures-in-regression-with-6a884810a692\">Introduction to the Finite Normal Mixtures in Regression with<\/a> was originally published in <a href=\"https:\/\/towardsdatascience.com\/\">Towards Data Science<\/a> on Medium, where people are continuing the conversation by highlighting and responding to this story.<\/p>\n<\/div>\n<p> \t<BR><br \/>\n <BR><\/BR><br \/>\n    Lukasz Gatarek<br \/>\n \t<BR><br \/>\n<BR><\/BR><br \/>\n<a href=\"https:\/\/medium.com\/m\/global-identity-2?redirectUrl=https%3A%2F%2Ftowardsdatascience.com%2Fintroduction-to-the-finite-normal-mixtures-in-regression-with-6a884810a692\">Go to original source<\/a><br \/>\n \t<BR><br \/>\n <BR><\/BR><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction to the Finite Normal Mixtures in Regression with Introduction to the Finite Normal Mixtures in Regression with\u00a0R How to make linear regression flexible enough for non-linear data The linear regression is usually considered not flexible enough to tackle the nonlinear data. From theoretical viewpoint it is not capable to dealing with them. However, we [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[62,984,177,983,985,986],"tags":[103,987,336],"class_list":["post-855","post","type-post","status-publish","format-standard","hentry","category-aimldsaimlds","category-bayesian-machine-learning","category-bayesian-statistics","category-mcmc-sampling","category-mixture-distribution","category-regression-analysis","tag-model","tag-normal","tag-regression"],"_links":{"self":[{"href":"https:\/\/mailitics.com\/index.php\/wp-json\/wp\/v2\/posts\/855"}],"collection":[{"href":"https:\/\/mailitics.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mailitics.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mailitics.com\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/mailitics.com\/index.php\/wp-json\/wp\/v2\/comments?post=855"}],"version-history":[{"count":0,"href":"https:\/\/mailitics.com\/index.php\/wp-json\/wp\/v2\/posts\/855\/revisions"}],"wp:attachment":[{"href":"https:\/\/mailitics.com\/index.php\/wp-json\/wp\/v2\/media?parent=855"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mailitics.com\/index.php\/wp-json\/wp\/v2\/categories?post=855"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mailitics.com\/index.php\/wp-json\/wp\/v2\/tags?post=855"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}