贝叶斯线性回归(Bayesian linear regression)是使用统计学中贝叶斯推断(Bayesian inference)方法求解的线性回归(linear regression)模型。
贝叶斯线性回归将线性模型的参数视为随机变数(random variable),并通过模型参数(权重係数)的先验(prior)计算其后验(posterior)。贝叶斯线性回归可以使用数值方法求解,在一定条件下,也可得到解析型式的后验或其有关统计量。
贝叶斯线性回归具有贝叶斯统计模型的基本性质,可以求解权重係数的机率密度函式,进行线上学习以及基于贝叶斯因子(Bayes factor)的模型假设检验。
基本介绍
- 中文名:贝叶斯线性回归
- 外文名:Bayesian linear regression
- 类型:回归算法
- 提出者:Dennis Lindley,Adrian Smith
- 提出时间:1972年
- 学科:统计学
历史
理论与算法
模型











求解


























































import numpy as npimport matplotlib.pyplot as plt# 构建测试数据## 自变数:[0,5]区间均匀分布x = np.random.uniform(low=0, high=5, size=5)## 因变数:y=2x-1+eps, eps=norm(0, 0.5)y = np.random.normal(2*x-1, 0.5)def calculate_csd(x, y, w1, w2, s, N, hyper_param): ''' 条件採样分布函式: (w1, w2, s) x , y: 输入数据 w1, w2: 线性回归模型的截距和斜率 s: 残差方差 N: 样本量 ''' # 超参数 mu1, s1 = hyper_param["mu1"], hyper_param['s1'] mu2, s2 = hyper_param["mu2"], hyper_param['s2'] a, b, = hyper_param["a"], hyper_param["b"] # 计算方差 var1 = (s1*s)/(s+s1*N) var2 = (s*s2)/(s+s2*np.sum(x*x)) # 计算均值 mean1 = (s*mu1+s1*np.sum(y-w2*x))/(s+s1*N) mean2 = (s*mu2+s2*np.sum((y-w1)*x))/(s+s2*np.sum(x*x)) # 计算(a, b) eps = y-w1-w2*x a = a+N/2; b = b+np.sum(eps*eps)/2 # 使用numpy.random採样(inv-gamma=1/gamma) # 注意numpy.random中normal和gamma的定义方式: ## np.random.normal(mean, std) ## inv-Gamma = 1/np.random.gamma(a, scale), scale=1/b return np.random.normal(mean1, np.sqrt(var1)), np.random.normal(mean2, np.sqrt(var2)), 1/np.random.gamma(a, 1/b)def Gibbs_sampling(x, y, iters, init, hyper_param): ''' 吉布斯採样算法主程式 iter: 叠代次数 init: 初始值 hyper_param: 超参数 ''' N = len(y) # 样本量 # 採样初始值 w1, w2, s = init["w1"], init["w2"], init["s"] # 使用数组记录叠代值 history = np.zeros([iters, 3])*np.nan # for循环叠代 for i in range(iters): w1, w2, s = calculate_csd(x, y, w1, w2, s, N, hyper_param) history[i, :] = np.array([w1, w2, s]) return history# 开始採样iters = 10000 # MCMC叠代1e4次init = {'w1': 0, 'w2': 0, 's': 0}hyper_param = {'mu1': 0, 's1': 1, 'mu2': 0, 's2': 1, 'a': 2, 'b': 1}history = Gibbs_sampling(x, y, iters, init, hyper_param)burnt = history[500:] # 截取收敛后的马尔可夫链ax1 = plt.subplot(2, 1, 1); ax2 = plt.subplot(2, 1, 2)ax1.hist(burnt[:, 0], bins=100)ax1.text(2, 0.025*iters, '$mathrm{N(w_1|mu,s)}$', fontsize=14)ax2.hist(burnt[:, 1], bins=100)ax2.text(.5, 0.025*iters, '$mathrm{N(w_2|mu,s)}$', fontsize=14)
预测





性质

