【ML】线性回归的吉布斯采样(Gibbs Sampling)实现(python)

article/2025/9/19 10:32:22

导航

Bayesian Linear Regression

考虑只有一个自变量(independent variable)的线性回归的情况,拟合数据对 ( y i , x i ) , i = 1 , 2 , … , N (y_i, x_i), i=1,2,\dots, N (yi,xi),i=1,2,,N,需要找出后验分布中的截距(intercept) β 0 \beta_0 β0和斜率/梯度(gradient)以及精度 τ \tau τ(方差的倒数,the reciprocal of the variance),模型可以表示为
y i ∼ N ( β 0 + β 1 x i , 1 / τ ) y_i\sim\mathcal{N}(\beta_0+\beta_1x_i, 1/\tau) yiN(β0+β1xi,1/τ)
或者等价的
y i = β 0 + β 1 x i + ε , ε ∼ N ( 0 , 1 / τ ) y_i=\beta_0+\beta_1x_i+\varepsilon, \varepsilon\sim\mathcal{N}(0, 1/\tau) yi=β0+β1xi+ε,εN(0,1/τ)
模型的似然函数可以被表示为 N N N个i.i.d观测点的乘积
L ( y 1 , … , y N , x 1 , x 2 , … , x N ∣ β 0 , β 1 , τ ) = ∏ i = 1 N N ( β 0 + β 1 x i , 1 / τ ) L(y_1, \dots, y_N, x_1, x_2, \dots, x_N\mid\beta_0, \beta_1, \tau)=\prod_{i=1}^N\mathcal{N}(\beta_0+\beta_1x_i, 1/\tau) L(y1,,yN,x1,x2,,xNβ0,β1,τ)=i=1NN(β0+β1xi,1/τ)
希望设置 β 0 , β 1 , τ \beta_0, \beta_1, \tau β0,β1,τ得到共轭先验, conjugate priors
{ β 0 ∼ N ( μ 0 , 1 / τ 0 ) β 1 ∼ N ( μ 1 , 1 / τ 1 ) τ ∼ Γ ( α , β ) \left\{ \begin{aligned} &\beta_0\sim \mathcal{N}(\mu_0, 1/\tau_0)\\ &\beta_1\sim \mathcal{N}(\mu_1, 1/\tau_1)\\ &\tau\sim \Gamma(\alpha, \beta) \end{aligned} \right. β0N(μ0,1/τ0)β1N(μ1,1/τ1)τΓ(α,β)

Gibbs Sampling

吉布斯采样的工作流程如下,假设我们有两个参数 θ 1 \theta_1 θ1 θ 2 \theta_2 θ2以及一些数据 x x x,目标是找到后验分布 p ( θ 1 , θ 2 ∣ x ) p(\theta_1, \theta_2\mid x) p(θ1,θ2x).

To do this in a Gibbs sampling regime, we need to work out the conditional distributions p ( θ 1 ∣ θ 1 , x ) p(\theta_1\mid \theta_1, x) p(θ1θ1,x) and p ( θ 2 ∣ θ 1 , x ) p(\theta_2\mid \theta_1, x) p(θ2θ1,x).

采样算法流程如下:

  1. 选择初始参数 θ 2 ( i + 1 ) \theta_2^{(i+1)} θ2(i+1)
  2. 采样 θ 1 ( i + 1 ) ∼ p ( θ 1 ∣ θ 2 ( i ) , x ) \theta_1^{(i+1)}\sim p(\theta_1\mid \theta_2^{(i)}, x) θ1(i+1)p(θ1θ2(i),x)
  3. 采样 θ 2 i + 1 ∼ p ( θ 2 ∣ θ 1 ( i + 1 ) , x ) \theta_2^{i+1}\sim p(\theta_2\mid\theta_1^{(i+1)}, x) θ2i+1p(θ2θ1(i+1),x)
    流程重复 K K K轮,可以采集到 K K K个样本.

The key thing to remember in Gibbs sampling is to always use the most recent parameter values for all samples (e.g. sample θ 2 ( i + 1 ) ∼ p ( θ 2 ∣ θ 1 ( i + 1 ) , x ) \theta_2^{(i+1)}\sim p(\theta_2\mid \theta_1^{(i+1)}, x) θ2(i+1)p(θ2θ1(i+1),x) and not θ 2 i + 1 ∼ p ( θ 2 ∣ θ 1 ( i ) , x ) \theta_2^{i+1}\sim p(\theta_2\mid \theta_1^{(i)}, x) θ2i+1p(θ2θ1(i),x) provided θ 1 ( i + 1 ) \theta_1^{(i+1)} θ1(i+1) has already been sampled).
The massive advantage of Gibbs sampling over other MCMC methods (namely Metropolis-Hastings) is that no tuning parameters are required.

Derving a Gibbs sampler

推导步骤如下

  1. Write down the posterior conditional density in log-form
  2. Throw away all terms that don’t depend on the current sampling variable
  3. Pretend this is the density for your variable of interest and all other variables are fixed. What distribution does the log-density remind of?

Update for β 0 \beta_0 β0

由贝叶斯公式可以得到
p ( β 0 ∣ β 1 , τ , y , x ) ∝ p ( y , x ∣ β 0 , β 1 , τ ) p ( β 0 ) p(\beta_0\mid \beta_1, \tau, y, x)\propto p(y, x \mid \beta_0, \beta_1, \tau)p(\beta_0) p(β0β1,τ,y,x)p(y,xβ0,β1,τ)p(β0)
其中 p ( y , x ∣ β 0 , β 1 , τ ) p(y, x\mid \beta_0, \beta_1, \tau) p(y,xβ0,β1,τ)是似然函数.
如果变量 x x x服从期望为 μ \mu μ,精度为 τ \tau τ的正态分布,关于 x x x的对数项(the log-dependence on x)为
τ 2 ( x − μ ) 2 ∝ − τ 2 x 2 + τ μ x \frac{\tau}{2}(x-\mu)^2\propto -\frac{\tau}{2}x^2+\tau\mu x 2τ(xμ)22τx2+τμx
对数形式下关于 β 0 \beta_0 β0的项为
− τ 0 2 ( β 0 − μ 0 ) 2 − τ 2 ∑ i = 1 N ( y i − β 0 − β 1 x i ) 2 -\frac{\tau_0}{2}(\beta_0-\mu_0)^2-\frac{\tau}{2}\sum_{i=1}^N(y_i-\beta_0-\beta_1x_i)^2 2τ0(β0μ0)22τi=1N(yiβ0β1xi)2

Although it is perhaps not obvious, this expression is quadratic in β 0 \beta_0 β0, meaning the conditional sampling density for β 0 \beta_0 β0 will also be normal. A bit of algebra(dropping all terms that do not involve β 0 \beta_0 β0) is

− τ 0 2 β 0 2 + τ 0 μ 0 β 0 − τ 2 N β 0 2 − τ ∑ i = 1 N ( y i − β 1 x i ) β 0 -\frac{\tau_0}{2}\beta_0^2+\tau_0\mu_0\beta_0-\frac{\tau}{2}N\beta_0^2-\tau\sum_{i=1}^N(y_i-\beta_1x_i)\beta_0 2τ0β02+τ0μ0β02τNβ02τi=1N(yiβ1xi)β0
即可以知道
β 0 \beta_0 β0的系数为 τ 0 μ 0 + τ ∑ i ( y i − β 1 x i ) \tau_0\mu_0+\tau\sum_i(y_i-\beta_1x_i) τ0μ0+τi(yiβ1xi)
β 0 2 \beta_0^2 β02的系数为 − τ 0 2 − τ 2 N -\frac{\tau_0}{2}-\frac{\tau}{2}N 2τ02τN
表示 β 0 \beta_0 β0的条件采样分布(conditional sampling distribution)为
β 0 ∣ β 1 , τ , τ 0 , μ 0 , x , y ∼ N ( τ 0 μ 0 + τ ∑ i ( y i − β 1 x i ) τ 0 + τ N , 1 / ( τ 0 + τ N ) ) \beta_0\mid\beta_1,\tau, \tau_0,\mu_0,x,y\sim\mathcal{N}\bigg(\frac{\tau_0\mu_0+\tau\sum_i(y_i-\beta_1x_i)}{\tau_0+\tau N}, 1/(\tau_0+\tau N)\bigg) β0β1,τ,τ0,μ0,x,yN(τ0+τNτ0μ0+τi(yiβ1xi),1/(τ0+τN))

def sample_beta_0(y, x, beta_1, tau, mu_0, tau_0):assert len(x)==len(y)N = len(y)precision=tau_0 + tau*Nmean = tau_0*mu_0+tau*np.sum(y-beta_1*x)mean /= precisionreturn random.normal(mean, 1/np.sqrt(precision)) # 得到beta_0采样

Update for β 1 \beta_1 β1

条件对数后验方程中关于 β 1 \beta_1 β1的项为
τ 1 2 ( β 1 − μ 1 ) 2 − τ 2 ∑ i = 1 N ( y i − β 0 − β 1 x i ) 2 \frac{\tau_1}{2}(\beta_1-\mu_1)^2-\frac{\tau}{2}\sum_{i=1}^N(y_i-\beta_0-\beta_1x_i)^2 2τ1(β1μ1)22τi=1N(yiβ0β1xi)2
展开得到
− τ 1 2 β 1 2 + τ 1 μ 1 β 1 − τ 2 ∑ i x i 2 β 1 2 + τ ∑ i ( y i − β 0 ) x i β 1 -\frac{\tau_1}{2}\beta_1^2+\tau_1\mu_1\beta_1-\frac{\tau}{2}\sum_ix_i^2\beta_1^2+\tau\sum_i(y_i-\beta_0)x_i\beta_1 2τ1β12+τ1μ1β12τixi2β12+τi(yiβ0)xiβ1
β 1 \beta_1 β1的系数为 τ 1 μ 1 + τ ∑ i ( y i − β 0 ) x i \tau_1\mu_1+\tau\sum_i(y_i-\beta_0)x_i τ1μ1+τi(yiβ0)xi β 1 2 \beta_1^2 β12的系数为 − τ 1 2 − τ 2 ∑ i x i 2 -\frac{\tau_1}{2}-\frac{\tau}{2}\sum_ix_i^2 2τ12τixi2,所以 β 1 \beta_1 β1的条件采样密度为
β 0 ∣ β 1 , τ , τ 0 , μ 0 , x , y ∼ N ( τ 0 μ 0 + τ ∑ i ( y i − β 1 x i ) τ 0 + τ N , 1 / ( τ 0 + τ N ) ) \beta_0\mid\beta_1,\tau, \tau_0,\mu_0, x, y\sim \mathcal{N}\bigg(\frac{\tau_0\mu_0+\tau\sum_i(y_i-\beta_1x_i)}{\tau_0+\tau N}, 1/(\tau_0+\tau N) \bigg) β0β1,τ,τ0,μ0,x,yN(τ0+τNτ0μ0+τi(yiβ1xi),1/(τ0+τN))

def sample_beta_1(y, x, beta_0, tau, mu_1, tau_1):assert len(x)==len(y)precision=tau_1+tau*np.sum(x*x)mean=tau_1*mu_1+tau*np.sum((y-beta_0)*x)mean/=precisionreturn random.normal(mean, 1/np.sqrt(precision)) 

Update for τ \tau τ

需要在non-Gaussian distributions下完成对 τ \tau τ值得更新,引入 Γ ( α , β ) \Gamma(\alpha, \beta) Γ(α,β)分布
p ( x ; α , β ) ∝ ( α − 1 ) log ⁡ x − β x p(x; \alpha, \beta)\propto (\alpha-1)\log x-\beta x p(x;α,β)(α1)logxβx
带回方程得到
p ( τ ∣ β 0 , β 1 , y , x ) ∝ p ( y , x ∣ β 0 ) p ( τ ) p(\tau\mid \beta_0, \beta_1, y, x)\propto p(y, x\mid \beta_0)p(\tau) p(τβ0,β1,y,x)p(y,xβ0)p(τ)
密度函数为
∏ i = 1 N N ( y i ∣ β 0 + β 1 x i ; 1 / τ ) × Γ ( τ ∣ α , β ) \prod_{i=1}^N \mathcal{N}(y_i\mid \beta_0+\beta_1x_i; 1/\tau)\times \Gamma(\tau\mid \alpha, \beta) i=1NN(yiβ0+β1xi;1/τ)×Γ(τα,β)
有概率密度函数的对数形式可以知道
N 2 log ⁡ τ − τ 2 ∑ i ( y i − β 0 − β 1 x i ) 2 + ( α − 1 ) log ⁡ τ − β τ \frac{N}{2}\log\tau-\frac{\tau}{2}\sum_i(y_i-\beta_0-\beta_1x_i)^2+(\alpha-1)\log\tau-\beta\tau 2Nlogτ2τi(yiβ0β1xi)2+(α1)logτβτ
根据系数可以知道
τ ∣ β 0 , β 1 , α , β , x , y ∼ Γ ( α + N 2 , β + ∑ i ( y i − β 0 − β 1 x i ) 2 2 ) \tau\mid\beta_0, \beta_1, \alpha, \beta, x, y\sim \Gamma(\alpha+\frac{N}{2}, \beta+\sum_i\frac{(y_i-\beta_0-\beta_1x_i)^2}{2}) τβ0,β1,α,β,x,yΓ(α+2N,β+i2(yiβ0β1xi)2)

Synthetic data

设置 β 0 = − 1 , β 1 = 2 , τ = 1 \beta_0=-1, \beta_1=2, \tau=1 β0=1,β1=2,τ=1为真实参数

def synthetic_data():beta_0_true=-1beta_1_true=2tau_true=1N=50x=random.uniform(low=0, high=4, size=N)y=random.normal(beta_0_true+beta_1_true*x, 1/np.sqrt(tau_true))syn_plt=plt.plot(x, y, 'o')plt.xlabel('x(uni. dist.)')plt.ylabel('y(normal dist.)')plt.grid(True)plt.show()

syn_data

Gibbs sampler

设置 β 0 , β 1 \beta_0,\beta_1 β0,β1服从先验为 N ( 0 , 1 ) \mathcal{N}(0, 1) N(0,1) τ \tau τ服从先验 Γ ( 2 , 1 ) \Gamma(2, 1) Γ(2,1)

x, y, N = synthetic_data()# 设置参数起点
init={'beta_0':0, 'beta_1':0, 'tau':2}
# 超参数
hypers={'mu_0': 0, 'tau_0':1, 'mu_1':0, 'tau_1':1, 'alpha':2, 'beta': 1}def gibbs(y, x, iters, init, hypers):assert len(x)==len(y)beta_0, beta_1, tau=init['beta_0'], init['beta_1'], init['tau']param_rec = np.zeros((iters, 3)) # 记录参数的变化for i in range(iters):beta_0=sample_beta_0(y, x, beta_1, tau, hypers['mu_0'], hypers['tau_0'])beta_1=sample_beta_1(y, x, beta_0, tau, hypers['mu_1'], hypers['tau_1'])tau = sample_tau(y, x, beta_0, beta_1, hypers['alpha'], hypers['beta'], N)param_rec[i, :]=np.array((beta_0, beta_1, tau))param_rec = DataFrame(param_rec)param_rec.columns=['beta_0', 'beta_1', 'tau']return param_recdef params():iters=1000 # 设置迭代轮数param_rec = gibbs(y, x, iters, init, hypers)it = [*range(1, iters+1)]beta_0 = param_rec['beta_0'].valuesbeta_1 = param_rec['beta_1'].valuestau = param_rec['tau'].valuesplt.plot(it, beta_0, '-.', color='b', linewidth=1, label='beta_0')plt.plot(it, beta_1, '-.', color='r', linewidth=1, label='beta_1')plt.plot(it, tau, '-.', color='g', linewidth=1, label='tau')plt.grid(True)plt.legend(loc='best')plt.show()params()

得到采样参数变化路径如下
params从采样结果可以发现,开始采样时,参数波动比较大,后来逐渐在真实值附近波动.

Even if it is obvious that the variables converge early it is convention to define a burn-in period where we assume the parameters are still converging, which is typically half of iterations. Therefore, we could check the final 500 iterations called trace_burnt

考察采样后半部分的参数

def trace_burnt():iters=1000param_rec = gibbs(y, x, iters, init, hypers)[500:-1]print(param_rec.median()) # 采样得到参数的中位数print(param_rec.std())    # 采样得到参数的标准差hist_plot = param_rec.hist(bins=30, layout=(1, 3))plt.show()

trace_burnt

code downlaod

Gibbs sampling python code

References

seaborn画图
Bayesian Data Analysis
Gibbs Sampling
Gibbs sampling for Bayesian linear regression
Markov Chain Monte Carlo(MCMC)
Gibbs采样完整解析与理解


http://chatgpt.dhexx.cn/article/O8qoEBdy.shtml

相关文章

【机器学习】主题建模+隐狄利克雷分配模型(LDA)+吉布斯采样

【主题建模】 大数据时代,面对海量的数据,如果能知道它的主题是什么,从数据压缩的角度来看,我们可以通过很少量的主题来管理很大亮的文档数据集合,从而实现一个比较简洁的操作和管理文档集合的目的;除此之外…

【人工智能】对贝叶斯网络进行吉布斯采样

问题 现要求通过吉布斯采样方法,利用该网络进行概率推理(计算 P(RT|SF, WT)、P2(CF|WT)的概率值)。 原理 吉布斯采样的核心思想为一维一维地进行采样,采某一个维度的时候固定其他的维度,在本次实验中,假…

matlab bnt工具箱吉布斯采样,吉布斯采样——原理及matlab实现

原文来自:https://victorfang.wordpress.com/2014/04/29/mcmc-the-gibbs-sampler-simple-example-w-matlab-code/ 【注】评论区有同学指出译文理论编码有误,请参考更官方的文献,个人当时仅验证过红色字体部分理论与维基百科中二位随机变量吉布斯采样的结果是否对应,其余部分…

【LDA】吉布斯采样

吉布斯采样是用条件概率得到联合概率分布。 其实是得到我们想要东西的近似解 目录 1 蒙特卡罗2 马尔科夫链3.MCMC采样4 MH采样5 吉布斯采样 1 蒙特卡罗 蒙特卡洛方法是为了解决一些不太好求解的求和或者积分问题。 其实就是一个近似方法,通过采样的多个样本代替原…

机器学习笔记之马尔可夫链蒙特卡洛方法(四)吉布斯采样

机器学习笔记之马尔可夫链蒙特卡洛方法——吉布斯采样 引言回顾:MH采样算法基于马尔可夫链的采样方式细致平衡原则与接收率 MH采样算法的弊端吉布斯采样方法吉布斯采样的采样过程吉布斯采样的推导过程吉布斯采样的代码实现 引言 上一节介绍了将马尔可夫链与蒙特卡洛…

三步完成吉布斯采样Gibbs sampling

吉布斯采样的具体执行过程只需要三个步骤,非常非常简单好理解,其它相关的背景知识能帮助加深理解。 一、Preliminaries Monte Carlo methods 它是很宽泛的一类计算方法,依赖重复的随机采样去获得数值结果。a broad class of computational a…

MCMC笔记:吉布斯采样(Gibbs)

1 介绍 吉布斯采样是一种特殊的MH采样 MCMC笔记Metropilis-Hastings算法(MH算法)_UQI-LIUWJ的博客-CSDN博客 此时我们要采样的分布是一个高维的情况 吉布斯采样的思想就是一维一维地进行采样,采某一个维度的时候固定其他的维度 吉布斯采…

吉布斯采样

回顾一下MC 采样: f(x)是已知 的概率分布函数,现在 找到一系列的x服从这个概率分布。也就是在f(x)当中抽取一些样本x。后来就提出了: F(x)是f(x)的累积概率分布,只需 在0到1上均匀采样得到i,然后将这个样本…

随机采样和随机模拟:吉布斯采样Gibbs Sampling

http://blog.csdn.net/pipisorry/article/details/51373090 吉布斯采样算法详解 为什么要用吉布斯采样 通俗解释一下什么是sampling。 sampling就是以一定的概率分布,看发生什么事件。举一个例子。甲只能E:吃饭、学习、打球,时间T&#xff1a…

吉布斯抽样

吉布斯采样是生成马尔科夫链的一种方法,生成的马尔科夫链可以用来做蒙特卡洛仿真,从而求得一个较复杂的多元分布。 吉布斯采样的具体做法:假设有一个k维的随机向量,现想要构造一条有n个样本的k维向量(n样本马尔科夫序列…

从马尔科夫过程到吉布斯采样(附程序示例)

目标:如何采取满足某个概率分布的一组数据,比如如何给出满足标准正太分布的1000个点,当然该分布比较简单,生成满足此分布的1000个点并不难,对matlab,python 等都是一行语句的事,但是如果是一个不…

sqlloader导出数据指定分隔符_来一份数据库全家桶~

♫. ♪ ~ ♬..♩~ ♫. ♪..♩~ ♫. ♪ ~ ♬..♩..♩~ ♫. ♪ ~ ♬..♩..♩~ ♫. ♪ ~ ♬..♩♫. ♪ ~ ♬..♩~ ♫. ♪..♩~ ♫. ♪ ~ ♬..♩..♩~ ♫. ♪ ~ ♬..♩..♩~ ♫. ♪ ~ ♬..♩ 点击蓝字关注我们♫. ♪ ~ ♬..♩~ ♫. ♪..♩~ ♫. ♪ ~ ♬..♩..♩~ ♫. ♪ ~ ♬..♩..…

使用sqlloader导入数据(千万级)-oracle

前言:笔者业务场景:当前表无分区,需将数据导出,创建分区后,重新导入当前表;当然,该方法同样使用于普通的数据迁移,或新旧表数据同步(表结构一致) 一、涉及数…

oracle-sqlloader的简单使用

目录 使用场景 简单使用 编写ctl文件 执行命令 使用场景 当你拿到一个txt文件,里面的数据是用统一符号分割的,例如如下文件,就可以考虑使用sqlloader导入到oracle数据库。 简单使用 编写ctl文件 OPTIONS (skip1,rows128) -- sqlldr 命…

使用Sqlloader处理数据

Oracle数据导出工具sqluldr2可以将数据以csv、txt等文件格式导出,适用于大批量数据的导出,导出速度非常快,导出后可以使用Oracle SQL Loader工具将数据导入到数据库中。下面将介绍Sqluldr2和sqlldr在Windows平台下的数据处理过程。 一、获取…

oracle之sqlloader

oracle的sqlloader可以从文件批量的将数据插入到数据库中,避免了使用SQL一句一句插入给数据库带来的压力。在工作中,简单的使用了一下,并没有深入的研究,下面是一个例子。 ① 数据文件信息: tina,12,34…

oracle sqlloader 的简单使用

1、EMP1 建表语句: CREATE TABLE EMP1 (EMPNO NUMBER(8) NOT NULL,ENAME VARCHAR2(10),HIREDATE DATE,JOB VARCHAR2(20),SAL NUMBER(8),DEPTNO NUMBER(8) NOT NULL ); 2、test.txt 数据文件: 1|Abandon1|2022-02-01|销售人员1|2500…

linux sql*loader-704,初见Oracle SqlLoader工具

因为大量的数据存在于文本文件中,需要导入到Oracle,有幸接触到神器SqlLoader. 在安装好Oracle的主机上单独运行sqlldr命令 sqlldr 将看到关于此工具的说明: 也只是简单的一个例子,帮助初次接触的你。 编写一个ctl文件,Oracle数据库…

mysql sql loader_Sql Loader的简单使用

之前总结的关于SQL*Loader的用法,今天又用到,又翻出来看看 SQL*Loader 可将外部文件中的数据加载到Oracle DB的表中。它具有一个功能强大的数据分析引擎,因此对数据文件中数据的格式没有什么限制。 SQL*Loader 使用以下文件:输入数…

Linux中sql*loader-350,SqlLoader

Sqlloader的步骤 1) Oracle 数据库端必须已经建好了需要导入的数据表的结构 2) 存在数据源文件 3) 手工编辑一个XXX.CTL 的控制文件 4) 命令行加载数据 Sqlldr命令具体信息如下图 Sqlldr运行的一个具体例子 sqlldr userid=user1/123456 control=bcp1.ctl log=log/bcp1.log bad=…