news 2026/4/29 1:28:09

使用 R 进行回归的有限正态混合模型介绍

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
使用 R 进行回归的有限正态混合模型介绍

原文:towardsdatascience.com/introduction-to-the-finite-normal-mixtures-in-regression-with-6a884810a692?source=collection_archive---------7-----------------------#2024-11-15

如何使线性回归足够灵活以处理非线性数据

https://medium.com/@lukaszgatarek81?source=post_page---byline--6a884810a692--------------------------------https://towardsdatascience.com/?source=post_page---byline--6a884810a692-------------------------------- Lukasz Gatarek

·发表于Towards Data Science ·阅读时长 8 分钟·2024 年 11 月 15 日

线性回归通常被认为不够灵活,无法处理非线性数据。从理论角度来看,它无法应对这些数据。然而,通过在回归模型中使用有限正态混合模型,我们可以使其适用于任何数据集。这样,它就成为一个非常强大的机器学习工具,可以应用于几乎任何数据集,甚至是高度非正态且变量间具有非线性依赖的数据集。

这种方法特别有趣的地方在于其可解释性。尽管具有极高的灵活性,所有检测到的关系都可以直接解释。该模型与神经网络一样具有普适性,但它并不会变成一个黑盒子。你可以读取这些关系,并理解各个变量的影响。

在这篇文章中,我们展示了如何使用马尔可夫链蒙特卡洛(MCMC)采样来模拟回归的有限混合模型。我们将生成具有多个成分(组)的数据,并拟合一个混合模型,通过贝叶斯推断来恢复这些成分。这个过程涉及回归模型和混合模型,并结合 MCMC 技术进行参数估计。

https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/36ff117a1f0b195a0c5ab4c72153b45e.png

数据模拟为三个线性回归的混合

加载所需的库

我们首先加载必要的库,以便处理回归模型、MCMC 和多元分布。

# Loading the required libraries for various functionslibrary("pscl")# For pscl specific functions, like regression modelslibrary("MCMCpack")# For MCMC sampling functions, including posterior distributionslibrary(mvtnorm)# For multivariate normal distribution functio

数据生成

我们模拟一个数据集,其中每个观测值属于多个组之一(混合模型的组分),响应变量是使用回归模型生成的,并且具有随机系数。

我们考虑一个使用 G 个正态混合组件的回归模型的通用设置。

https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/3ed53e8272456985255a39c1e2290cd9.png

## Generate the observations# Set the length of the time series (number of observations per group)N<-1000# Set the number of simulations (iterations of the MCMC process)nSim<-200# Set the number of components in the mixture model (G is the number of groups)G<-3

数据模拟

每个组都使用单变量回归模型进行建模,其中解释变量(X)和响应变量(y)是从正态分布中模拟出来的。betas表示每个组的回归系数,sigmas表示每个组的方差。

# Set the values for the regression coefficients (betas) for each groupbetas<-1:sum(dimG)*2.5# Generating sequential betas with a multiplier of 2.5# Define the variance (sigma) for each component (group) in the mixturesigmas<-rep(1,G)/1# Set variance to 1 for each component, with a fixed divisor of 1

在这个模型中,我们允许每个混合组分拥有自己的方差参数和回归参数集。

组分配和混合

然后我们使用随机分配模拟每个观测值的组分配,并将所有组件的数据混合在一起。

我们通过一组组件标签向量来扩展模型,以表示

https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/eb047a04981f3687cebbe80278b29314.png

其中

https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/9756b038c770fa78ab6fd85e875d98dc.png

因此,z_gi=1表示第i个个体来自混合模型的第g个组分。

这种随机分配形成了z_original向量,表示每个观测值所属的真实组。

# Initialize the original group assignments (z_original)z_original<-matrix(NA,N*G,1)# Repeat each group label N times (assign labels to each observation per group)z_original<-rep(1:G,rep(N,G))# Resample the data rows by random ordersampled_order<-sample(nrow(data))# Apply the resampled order to the datadata<-data[sampled_order,]

贝叶斯推断:先验分布与初始化

我们为回归系数和方差设置了先验分布。这些先验将指导我们的贝叶斯估计。

https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/66c79c39852ac0490d55a7958de9afa6.png

## Define Priors for Bayesian estimation# Define the prior mean (muBeta) for the regression coefficientsmuBeta<-matrix(0,G,1)# Define the prior variance (VBeta) for the regression coefficientsVBeta<-100*diag(G)# Large variance (100) as a prior for the beta coefficients# Prior for the sigma parameters (variance of each component)ag<-3# Shape parameterbg<-1/2# Rate parameter for the prior on sigmashSigma<-ag raSigma<-bg^(-1)

对于组件指示符和组件概率,我们考虑以下先验分配。

https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/32c364a60b362d26cc314efdca7072ba.png

多项式先验 M 是二项分布的多变量推广,而 Dirichlet 先验 D 是贝塔分布的多变量推广。

MCMC 初始化

在本节中,我们通过设置矩阵来初始化 MCMC 过程,以存储回归系数、方差和混合比例的样本。

## Initialize MCMC sampling# Initialize matrix to store the samples for betamBeta<-matrix(NA,nSim,G)# Assign the first value of beta using a random normal distributionfor(gin1:G){mBeta[1,g]<-rnorm(1,muBeta[g,1],VBeta[g,g])}# Initialize the sigma² values (variance for each component)mSigma2<-matrix(NA,nSim,G)mSigma2[1,]<-rigamma(1,shSigma,raSigma)# Initialize the mixing proportions (pi), using a Dirichlet distributionmPi<-matrix(NA,nSim,G)alphaPrior<-rep(N/G,G)# Prior for the mixing proportions, uniform across groupsmPi[1,]<-rdirichlet(1,alphaPrior)

MCMC 采样:后验更新

如果我们在组件指示变量 z 的值上进行条件化,则条件似然可以表示为

https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/a03f350ff3f9294c59770a83f1abc56c.png

在 MCMC 采样循环中,我们基于后验分布更新组分配(z)、回归系数(beta)和方差(sigma)。计算每个组分配的似然,并选择具有最高后验概率的组。

以下完整的后验条件可以得到:

https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/a7d1f5bcc4952cfa4ab1f0d36e1478a4.png

其中

https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/aaf3ceb5f34ba16009e704d76e351267.png

表示后验中的所有参数,除了x

https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/b9f326d43e2c0dc83726a042e1f3adff.png

其中,n_g表示混合模型中第g个组的观测数。

https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/220beb5af0688c95c858473ae05d9b2c.png

https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/f9b9da480f7230033270068a2921f3d3.png

以下算法按照顺序从上面的后验分布系列中提取样本。

## Start the MCMC iterations for posterior sampling# Loop over the number of simulationsfor(iin2:nSim){print(i)# Print the current iteration number# For each observation, update the group assignment (z)for(tin1:(N*G)){fig<-NULLfor(gin1:G){# Calculate the likelihood of each group and the corresponding posterior probabilityfig[g]<-dnorm(y[t,1],X[t,]%*%mBeta[i-1,g],sqrt(mSigma2[i-1,g]))*mPi[i-1,g]}# Avoid zero likelihood and adjust itif(all(fig)==0){fig<-fig+1/G}# Sample a new group assignment based on the posterior probabilitiesz[i,t]<-which(rmultinom(1,1,fig/sum(fig))==1)}# Update the regression coefficients for each groupfor(gin1:G){# Compute the posterior mean and variance for beta (using the data for group g)DBeta<-solve(t(X[z[i,]==g,])%*%X[z[i,]==g,]/mSigma2[i-1,g]+solve(VBeta[g,g]))dBeta<-t(X[z[i,]==g,])%*%y[z[i,]==g,1]/mSigma2[i-1,g]+solve(VBeta[g,g])%*%muBeta[g,1]# Sample a new value for beta from the multivariate normal distributionmBeta[i,g]<-rmvnorm(1,DBeta%*%dBeta,DBeta)# Update the number of observations in group gng[i,g]<-sum(z[i,]==g)# Update the variance (sigma²) for each groupmSigma2[i,g]<-rigamma(1,ng[i,g]/2+shSigma,raSigma+1/2*sum((y[z[i,]==g,1]-(X[z[i,]==g,]*mBeta[i,g]))²))}# Reorder the group labels to maintain consistencyreorderWay<-order(mBeta[i,])mBeta[i,]<-mBeta[i,reorderWay]ng[i,]<-ng[i,reorderWay]mSigma2[i,]<-mSigma2[i,reorderWay]# Update the mixing proportions (pi) based on the number of observations in each groupmPi[i,]<-rdirichlet(1,alphaPrior+ng[i,])}

这段代码执行了 MCMC 中的关键步骤:

结果可视化

最后,我们可视化 MCMC 采样的结果。我们绘制每个回归系数的后验分布,将其与真实值进行比较,并绘制最可能的组分配。

# Plot the posterior distributions for each beta coefficientpar(mfrow=c(G,1))for(gin1:G){plot(density(mBeta[5:nSim,g]),main='True parameter (vertical) and the distribution of the samples')# Plot the density for the beta estimatesabline(v=betas[g])# Add a vertical line at the true value of beta for comparison}

该图显示了 MCMC 样本(后验分布)如何收敛到回归系数的真实值(betas)。

结论

通过这个过程,我们展示了如何在回归上下文中使用有限的正态混合模型,并结合 MCMC 进行参数估计。通过模拟具有已知分组的数据,并通过贝叶斯推断恢复参数,我们可以评估我们的模型在多大程度上捕捉到了数据的潜在结构。

除非另有说明,所有图像均为作者提供。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/23 11:12:46

PDF注释层添加OCR文本:使扫描版PDF变为可搜索文档

PDF注释层添加OCR文本&#xff1a;使扫描版PDF变为可搜索文档 在企业档案室、律所文件柜或高校图书馆里&#xff0c;成千上万份纸质文档正以“图像”的形式沉睡在PDF中。它们清晰可见&#xff0c;却无法被搜索、复制甚至理解——这正是传统扫描PDF的尴尬处境。一页合同里的“违…

作者头像 李华
网站建设 2026/4/22 21:36:43

1.24 LLM模型选择指南:Text2SQL场景下如何选择最适合的大模型

1.24 LLM模型选择指南:Text2SQL场景下如何选择最适合的大模型 引言 在Text2SQL场景下,选择合适的LLM模型至关重要。不同模型在SQL生成能力、准确率、成本等方面各有优劣。本文将深入解析如何选择最适合Text2SQL场景的大模型。 一、模型选择维度 1.1 选择维度 #mermaid-sv…

作者头像 李华
网站建设 2026/4/27 11:59:08

数学公式识别进阶:HunyuanOCR输出LaTeX格式的可能性探讨

数学公式识别进阶&#xff1a;HunyuanOCR输出LaTeX格式的可能性探讨 在科研论文写作、教学课件制作或技术文档排版中&#xff0c;数学公式的输入始终是一个“慢动作”环节。即便是熟练使用 LaTeX 的用户&#xff0c;面对复杂的积分、矩阵或嵌套分式时也难免出错&#xff1b;而对…

作者头像 李华
网站建设 2026/4/23 9:15:09

真实人物肖像还原度测评:lora-scripts训练效果实录

真实人物肖像还原度测评&#xff1a;lora-scripts训练效果实录 在AI生成内容日益普及的今天&#xff0c;我们已经能轻松用几个关键词画出奇幻风景、未来城市&#xff0c;甚至风格化的人物插画。但当用户真正想“复刻”一个真实存在的人——比如自己、家人&#xff0c;或是某位公…

作者头像 李华
网站建设 2026/4/27 23:41:53

暗黑3技能连点器D3KeyHelper完整教程:5步快速精通自动化操作

D3KeyHelper是一款专为暗黑破坏神3设计的鼠标宏工具&#xff0c;具备图形化界面和高度可配置的按键系统。这款完全免费的绿色软件能够显著提升游戏操作效率&#xff0c;让玩家专注于策略而非重复按键。 【免费下载链接】D3keyHelper D3KeyHelper是一个有图形界面&#xff0c;可…

作者头像 李华