解决方案

贝叶斯神经网络 BNN

seo靠我 2023-09-25 11:13:58

1. 简介

贝叶斯神经网络不同于一般的神经网络,其权重参数是随机变量,而非确定的值。如下图所示:

也就是说,和传统的神经网络用交叉熵,mse等损失函数去拟合标签值相反,贝叶斯神经网络拟合后验分布。

这样做的SEO靠我好处,就是降低过拟合。

2. BNN模型

BNN 不同于 DNN,可以对预测分布进行学习,不仅可以给出预测值,而且可以给出预测的不确定性。这对于很多问题来说非常关键,比如:机器学习中著名的 ExploraSEO靠我tion & Exploitation (EE)的问题,在强化学习问题中,agent 是需要利用现有知识来做决策还是尝试一些未知的东西;实验设计问题中,用贝叶斯优化来调超参数,选择下一个点是根据当前模SEO靠我型的最优值还是利用探索一些不确定性较高的空间。比如:异常样本检测,对抗样本检测等任务,由于 BNN 具有不确定性量化能力,所以具有非常强的鲁棒性

概率建模:

在这里,选择似然分布的共轭分布,这样后验可以SEO靠我分析计算。

比如,beta分布的先验和伯努利分布的似然,会得到服从beta分布的后验。

由于共轭分布,需要对先验分布进行约束。因此,我们尝试使用采用和变分推断来近似后验分布。

神经网络:

使用全连接网络来拟合SEO靠我数据,相当于使用多个全连接网络。

但是神经网络容易过拟合,泛化性差;并且对预测的结果无法给出置信度。

BNN: 把概率建模和神经网络结合起来,并能够给出预测结果的置信度。

先验用来描述关键参数,并作为神经网络SEO靠我的输入。神经网络的输出用来描述特定的概率分布的似然。通过采样或者变分推断来计算后验分布。

同时,和神经网络不同,权重 W 不再是一个确定的值,而是一个概率分布。

BNN建模如下:

假设 NN 的网络参数为 SEO靠我W W W, p ( W ) p(W) p(W) 是参数的先验分布,给定观测数据 D = X , Y D={X,Y} D=X,Y,这里 X X X 是输入数据, Y Y Y 是标签数据。BNN 希望给SEO靠我出以下的分布:

也就是我们预测值为:

P ( Y ⋆ ∣ X ⋆ , D ) = ∫ P ( Y ⋆ ∣ X ⋆ , W ) P ( W ∣ D ) d W ( 1 ) P\left(Y^{\star} SEO靠我| X^{\star}, D\right)=\int P\left(Y^{\star} | X^{\star}, W\right) P(W | D) d W (1) P(Y⋆∣X⋆,D)=∫P(Y⋆∣SEO靠我X⋆,W)P(W∣D)dW(1)

由于, W W W是随机变量,因此,我们的预测值也是个随机变量。

其中:

P ( W ∣ D ) = P ( W ) P ( D ∣ W ) P ( D ) ( 2 ) PSEO靠我(W | D)=\frac{P(W) P(D | W)}{P(D)} (2) P(W∣D)=P(D)P(W)P(D∣W)​(2)

这里 P ( W ∣ D ) P(W|D) P(W∣D) 是后验分布, SEO靠我P ( D ∣ W ) P(D|W) P(D∣W) 是似然函数, P ( D ) P(D) P(D) 是边缘似然。

从公式(1)中可以看出,用 BNN 对数据进行概率建模并预测的核心在于做高效近似后验推SEO靠我断,而 变分推断 VI 或者采样是一个非常合适的方法。

如果采样的话:

我们通过采样后验分布 P ( W ∣ D ) P(W \vert \mathcal{D}) P(W∣D) 来评估 P ( W ∣ DSEO靠我 ) P(W \vert \mathcal{D}) P(W∣D) , 每个样本计算 f ( X ∣ w ) f(X \vert w) f(X∣w), 其中 f 是我们的神经网络。

正是我们的输出是一个分SEO靠我布,而不是一个值,我们可以估计我们预测的不确定度。

3. 基于变分推断的BNN训练

如果直接采样后验概率 p ( W ∣ D ) p(W|D) p(W∣D) 来评估 p ( Y ∣ X , D ) p(YSEO靠我|X, D) p(Y∣X,D)的话,存在后验分布多维的问题,而变分推断的思想是使用简单分布去近似后验分布。

表示 θ = ( μ , σ ) \theta = (\mu, \sigma) θ=(μ,σ)SEO靠我, 每个权重 w i w_i wi​ 从正态分布 ( μ i , σ i ) (\mu_i, \sigma_i) (μi​,σi​) 中采样。

希望 q ( w ∣ θ ) q(w \vert \theSEO靠我ta) q(w∣θ) 和 P ( w ∣ D ) P(w \vert \mathcal{D}) P(w∣D) 相近,并使用 KL 散度来度量这两个分布的距离。

也就是优化:

θ ∗ = a r g m iSEO靠我 n θ KL [ q ( w ∣ θ ) ∣ ∣ P ( w ∣ D ) ] ( 3 ) \theta^* = \underset{\theta}{\mathrm{argmin}} \text{ KSEO靠我L}\left[q(w \vert \theta) \vert \vert P(w \vert \mathcal{D})\right] \; (3) θ∗=θargmin​ KL[q(w∣θ)∣∣P(SEO靠我w∣D)](3)

进一步推导:

θ ∗ = a r g m i n θ KL [ q ( w ∣ θ ) ∣ ∣ P ( w ∣ D ) ] = a r g m i n θ E q ( w ∣ θ ) [SEO靠我 log ⁡ [ q ( w ∣ θ ) P ( w ∣ D ) ] ] (definition of KL divegence) = a r g m i n θ E q ( w ∣ θ ) [ loSEO靠我g ⁡ [ q ( w ∣ θ ) P ( D ) P ( D ∣ w ) P ( w ) ] ] (Bayes Theorem) = a r g m i n θ E q ( w ∣ θ ) [ loSEO靠我g ⁡ [ q ( w ∣ θ ) P ( D ∣ w ) P ( w ) ] ] (Drop  P ( D ) because it doesn’t depend on  θ ) ( 4 ) \beSEO靠我gin{array}{l} \theta^* &= \underset{\theta}{\mathrm{argmin}} \text{ KL}\left[q(w \vert \theta) \vertSEO靠我 \vert P(w \vert \mathcal{D})\right] & \\\\ &= \underset{\theta}{\mathrm{argmin}} \text{ }\mathbb{E}SEO靠我_{q(w \vert \theta)}\left[ \log\left[\frac{ q(w \vert \theta) }{P( w \vert \mathcal{D})}\right]\righSEO靠我t] & \text{(definition of KL divegence)} \\\\ &= \underset{\theta}{\mathrm{argmin}} \text{ }\mathbb{SEO靠我E}_{q(w \vert \theta)}\left[ \log\left[\frac{ q(w \vert \theta)P(\mathcal{D}) }{P( \mathcal{D} \vertSEO靠我 w)P(w)}\right]\right] & \text{(Bayes Theorem)} \\\\ &= \underset{\theta}{\mathrm{argmin}} \text{ }\SEO靠我mathbb{E}_{q(w \vert \theta)}\left[ \log\left[\frac{ q(w \vert \theta) }{P( \mathcal{D} \vert w)P(w)SEO靠我}\right]\right] & \text{(Drop }P(\mathcal{D})\text{ because it doesnt depend on } \theta) \end{arraySEO靠我} \;(4) θ∗​=θargmin​ KL[q(w∣θ)∣∣P(w∣D)]=θargmin​ Eq(w∣θ)​[log[P(w∣D)q(w∣θ)​]]=θargmin​ Eq(w∣θ)​[log[SEO靠我P(D∣w)P(w)q(w∣θ)P(D)​]]=θargmin​ Eq(w∣θ)​[log[P(D∣w)P(w)q(w∣θ)​]]​(definition of KL divegence)(BayesSEO靠我 Theorem)(Drop P(D) because it doesn’t depend on θ)​(4)

公式中,

q ( w ∣ θ ) q(w|\theta) q(w∣θ) 表示给定正态分布的参SEO靠我数后,权重参数的分布;

P ( D ∣ w ) P(D|w) P(D∣w) 表示给定网络参数后,观测数据的似然;

P ( w ) P(w) P(w) 表示权重的先验,这部分可以作为模型的正则化。

并且使用

LSEO靠我 = − E q ( w ∣ θ ) [ log ⁡ [ q ( w ∣ θ ) P ( D ∣ w ) P ( w ) ] ] ( 5 ) \mathcal{L} = - \mathbb{E}_{qSEO靠我(w \vert \theta)}\left[ \log\left[\frac{ q(w \vert \theta) }{P( \mathcal{D} \vert w)P(w)}\right]\rigSEO靠我ht] \;(5) L=−Eq(w∣θ)​[log[P(D∣w)P(w)q(w∣θ)​]](5)

来表示变分下界ELBO, 也就是公式(4)等价于最大化ELBO:

L = ∑ i log ⁡ q ( w SEO靠我i ∣ θ i ) − ∑ i log ⁡ P ( w i ) − ∑ j log ⁡ P ( y j ∣ w , x j ) ( 6 ) \mathcal{L} = \sum_i \log q(w_SEO靠我i \vert \theta_i) - \sum_i \log P(w_i) - \sum_j \log P(y_j \vert w, x_j) \;(6) L=i∑​logq(wi​∣θi​)−i∑SEO靠我​logP(wi​)−j∑​logP(yj​∣w,xj​)(6)

其中, D = { ( x , y ) } D =\{ (x, y)\} D={(x,y)}

我们需要对公式(4)中的期望进行求导,但是,SEO靠我这里,我们使用对权重进行重参数的技巧:

w i = μ i + σ i × ϵ i ( 7 ) w_i = \mu_i + \sigma_i \times \epsilon_i \; (7) wi​=μSEO靠我i​+σi​×ϵi​(7)

其中, ϵ i ∼ N ( 0 , 1 ) \epsilon_i \sim \mathcal{N}(0,1) ϵi​∼N(0,1).

于是,用 ϵ \epsilon ϵ代 替 SEO靠我w w w 后有:

∂ ∂ θ E q ( ϵ ) [ log ⁡ [ q ( w ∣ θ ) P ( D ∣ w ) P ( w ) ] ] = E q ( ϵ ) [ ∂ ∂ θ log ⁡ [ qSEO靠我 ( w ∣ θ ) P ( D ∣ w ) P ( w ) ] ] ( 8 ) \frac{\partial}{\partial \theta}\mathbb{E}_{q(\epsilon)}\leSEO靠我ft[ \log\left[\frac{ q(w \vert \theta) }{P( \mathcal{D} \vert w)P(w)}\right]\right] =\mathbb{E}_{q(\SEO靠我epsilon)}\left[ \frac{\partial}{\partial \theta}\log\left[\frac{ q(w \vert \theta) }{P( \mathcal{D} SEO靠我\vert w)P(w)}\right]\right] \; (8) ∂θ∂​Eq(ϵ)​[log[P(D∣w)P(w)q(w∣θ)​]]=Eq(ϵ)​[∂θ∂​log[P(D∣w)P(w)q(w∣θSEO靠我)​]](8)

也就是说,我们可以通过 多个不同的 ϵ ∼ N ( 0 , 1 ) \epsilon \sim \mathcal{N}(0,1) ϵ∼N(0,1) ,求取 ∂ ∂ θ log ⁡ [ qSEO靠我 ( w ∣ θ ) P ( D ∣ w ) P ( w ) ] \frac{\partial}{\partial \theta}\log\left[\frac{ q(w \vert \theta) SEO靠我}{P( \mathcal{D} \vert w)P(w)}\right] ∂θ∂​log[P(D∣w)P(w)q(w∣θ)​] 的平均值,来近似 KL 散度对 θ \theta θ 的求导。

此外,除SEO靠我了对 w w w 进行重采样之外,为了保证 θ \theta θ 参数取值范围包含这个实轴,对 σ \sigma σ 进行重采样,可以令,

σ = log ⁡ ( 1 + e ρ ) ( 9 ) \siSEO靠我gma = \log (1 + e^{\rho}) \;\;\; (9) σ=log(1+eρ)(9)

然后, θ = ( μ , ρ ) \theta = (\mu, \rho) θ=(μ,ρ),这里SEO靠我的 θ \theta θ 已经和原来定义的 θ = ( μ , σ ) \theta = (\mu, \sigma) θ=(μ,σ) 不一样了。

4. BNN实践

算法:

从 N ( μ , l o g (SEO靠我 1 + e ρ ) ) N(\mu, log(1+e^\rho)) N(μ,log(1+eρ)) 中采样,获得 w w w;分别计算 log ⁡ q ( w ∣ θ ) \log q(w|\thetSEO靠我a) logq(w∣θ)、 log ⁡ p ( w ) \log p(w) logp(w)、 log ⁡ p ( y ∣ w , x ) \log p(y|w,x) logp(y∣w,x).

其中,计算SEO靠我 log ⁡ p ( y ∣ w , x ) \log p(y|w,x) logp(y∣w,x) 实际计算 log ⁡ p ( y ∣ y p r e d ) \log p(y|y_{pred}) lSEO靠我ogp(y∣ypred​), y p r e d = w ∗ x y_{pred} = w*x ypred​=w∗x.

也就可以得到 L = ∑ i log ⁡ q ( w i ∣ θ i ) − ∑ SEO靠我i log ⁡ P ( w i ) − ∑ j log ⁡ P ( y j ∣ w , x j ) \mathcal{L} = \sum_i \log q(w_i \vert \theta_i) - SEO靠我\sum_i \log P(w_i) - \sum_j \log P(y_j \vert w, x_j) L=∑i​logq(wi​∣θi​)−∑i​logP(wi​)−∑j​logP(yj​∣w,xSEO靠我j​)。重复更新参数 θ ’ = θ − α ∇ θ L \theta’ = \theta -\alpha \nabla_\theta \mathcal{L} θ’=θ−α∇θ​L.

Pytorch实现SEO靠我

import torch import torch.nn as nn import torch.nn.functional as F import tSEO靠我orch.optim as optim from torch.distributions import Normal import numpy as np SEO靠我 from scipy.stats import norm import matplotlib.pyplot as pltclass Linear_BBB(nn.Module):""SEO靠我"Layer of our BNN."""def __init__(self, input_features, output_features, prior_var=1.):"""InitializaSEO靠我tion of our layer : our prior is a normal distributioncentered in 0 and of variance 20."""# initialiSEO靠我ze layerssuper().__init__()# set input and output dimensionsself.input_features = input_featuresselfSEO靠我.output_features = output_features# initialize mu and rho parameters for the weights of the layerselSEO靠我f.w_mu = nn.Parameter(torch.zeros(output_features, input_features))self.w_rho = nn.Parameter(torch.zSEO靠我eros(output_features, input_features))#initialize mu and rho parameters for the layers biasself.b_muSEO靠我 = nn.Parameter(torch.zeros(output_features))self.b_rho = nn.Parameter(torch.zeros(output_features))SEO靠我 #initialize weight samples (these will be calculated whenever the layer makes a prediction)self.w =SEO靠我 Noneself.b = None# initialize prior distribution for all of the weights and biasesself.prior = torcSEO靠我h.distributions.Normal(0,prior_var)def forward(self, input):"""Optimization process"""# sample weighSEO靠我tsw_epsilon = Normal(0,1).sample(self.w_mu.shape)self.w = self.w_mu + torch.log(1+torch.exp(self.w_rSEO靠我ho)) * w_epsilon# sample biasb_epsilon = Normal(0,1).sample(self.b_mu.shape)self.b = self.b_mu + torSEO靠我ch.log(1+torch.exp(self.b_rho)) * b_epsilon# record log prior by evaluating log pdf of prior at sampSEO靠我led weight and biasw_log_prior = self.prior.log_prob(self.w)b_log_prior = self.prior.log_prob(self.bSEO靠我)self.log_prior = torch.sum(w_log_prior) + torch.sum(b_log_prior)# record log variational posterior SEO靠我by evaluating log pdf of normal distribution defined by parameters with respect at the sampled valueSEO靠我sself.w_post = Normal(self.w_mu.data, torch.log(1+torch.exp(self.w_rho)))self.b_post = Normal(self.bSEO靠我_mu.data, torch.log(1+torch.exp(self.b_rho)))self.log_post = self.w_post.log_prob(self.w).sum() + seSEO靠我lf.b_post.log_prob(self.b).sum()return F.linear(input, self.w, self.b)class MLP_BBB(nn.Module):def _SEO靠我_init__(self, hidden_units, noise_tol=.1, prior_var=1.):# initialize the network like you would withSEO靠我 a standard multilayer perceptron, but using the BBB layersuper().__init__()self.hidden = Linear_BBBSEO靠我(1,hidden_units, prior_var=prior_var)self.out = Linear_BBB(hidden_units, 1, prior_var=prior_var)selfSEO靠我.noise_tol = noise_tol # we will use the noise tolerance to calculate our likelihooddef forward(selfSEO靠我, x):# again, this is equivalent to a standard multilayer perceptronx = torch.sigmoid(self.hidden(x)SEO靠我)x = self.out(x)return xdef log_prior(self):# calculate the log prior over all the layersreturn selfSEO靠我.hidden.log_prior + self.out.log_priordef log_post(self):# calculate the log posterior over all the SEO靠我layersreturn self.hidden.log_post + self.out.log_postdef sample_elbo(self, input, target, samples):#SEO靠我 we calculate the negative elbo, which will be our loss function#initialize tensorsoutputs = torch.zSEO靠我eros(samples, target.shape[0])log_priors = torch.zeros(samples)log_posts = torch.zeros(samples)log_lSEO靠我ikes = torch.zeros(samples)# make predictions and calculate prior, posterior, and likelihood for a gSEO靠我iven number of samplesfor i in range(samples):outputs[i] = self(input).reshape(-1) # make predictionSEO靠我slog_priors[i] = self.log_prior() # get log priorlog_posts[i] = self.log_post() # get log variationaSEO靠我l posteriorlog_likes[i] = Normal(outputs[i], self.noise_tol).log_prob(target.reshape(-1)).sum() # caSEO靠我lculate the log likelihood# calculate monte carlo estimate of prior posterior and likelihoodlog_prioSEO靠我r = log_priors.mean()log_post = log_posts.mean()log_like = log_likes.mean()# calculate the negative SEO靠我elbo (which is our loss function)loss = log_post - log_prior - log_likereturn lossdef toy_function(xSEO靠我):return -x**4 + 3*x**2 + 1# toy dataset we can start with x = torch.tensor([-2, -1.8, -1, 1SEO靠我, 1.8, 2]).reshape(-1,1) y = toy_function(x)net = MLP_BBB(32, prior_var=10) optimizeSEO靠我r = optim.Adam(net.parameters(), lr=.1) epochs = 2000 for epoch in range(epochs): # SEO靠我loop over the dataset multiple timesoptimizer.zero_grad()# forward + backward + optimizeloss = net.sSEO靠我ample_elbo(x, y, 1)loss.backward()optimizer.step()if epoch % 10 == 0:print(epoch: {}/{}.format(epochSEO靠我+1,epochs))print(Loss:, loss.item()) print(Finished Training)# samples is the number of "preSEO靠我dictions" we make for 1 x-value. samples = 100 x_tmp = torch.linspace(-5,5,100).reshSEO靠我ape(-1,1) y_samp = np.zeros((samples,100)) for s in range(samples):y_tmp = net(x_tmpSEO靠我).detach().numpy()y_samp[s] = y_tmp.reshape(-1) plt.plot(x_tmp.numpy(), np.mean(y_samp, axisSEO靠我 = 0), label=Mean Posterior Predictive) plt.fill_between(x_tmp.numpy().reshape(-1), np.perceSEO靠我ntile(y_samp, 2.5, axis = 0), np.percentile(y_samp, 97.5, axis = 0), alpha = 0.25, label=95% ConfideSEO靠我nce) plt.legend() plt.scatter(x, toy_function(x)) plt.title(Posterior PredicSEO靠我tive) plt.show()

这里是重复计算100次的平均值和100次平均值的97.5%大和2.5%小的区域线图(即置信度95%)。

最近开通了个公众号,主要分享深度学习相关内容,推荐SEO靠我系统,风控等算法相关的内容,感兴趣的伙伴可以关注下。

参考:

变分推断;Weight Uncertainty in Neural Networks Tutorial;Bayesian Neural NetSEO靠我works;原论文
“SEO靠我”的新闻页面文章、图片、音频、视频等稿件均为自媒体人、第三方机构发布或转载。如稿件涉及版权等问题,请与 我们联系删除或处理,客服邮箱:html5sh@163.com,稿件内容仅为传递更多信息之目的,不代表本网观点,亦不代表本网站赞同 其观点或证实其内容的真实性。

网站备案号:浙ICP备17034767号-2