Bayesian regression

前面介绍的线性模型都是从最小二乘,均方误差的角度去建立的,从最简单的最小二乘到带正则项的 lasso,ridge 等。而 Bayesian regression 是从 Bayesian 概率模型的角度出发的,虽然最后也会转换成一个能量函数的形式。

从前面的线性模型中,我们都假设如下的关系:

y=wx" role="presentation">y=wxy=wx

上面这个关系式其实是直接从值的角度来考虑,其实我们也可以假设如下的关系:

y=wx+ϵ" role="presentation">y=wx+ϵy=wx+ϵ

这个 ϵ" role="presentation" style="position: relative;">ϵϵ 表示一种误差,或者噪声,如果估计的值非常准确,那么 ϵ=0" role="presentation" style="position: relative;">ϵ=0ϵ=0, 否则,这将是一个随机数。

如果我们有一组训练样本,那么每个观察值 y" role="presentation" style="position: relative;">yy 都会有个对应的 ϵ" role="presentation" style="position: relative;">ϵϵ, 而且我们假设 ϵ" role="presentation" style="position: relative;">ϵϵ 是满足独立同分布的。那么我们可以用概率的形式表示为:

p(y|w,x,α)=N(y|wx,α)" role="presentation">p(y|w,x,α)=N(y|wx,α)p(y|w,x,α)=N(y|wx,α)

对于一组训练集,我们可以表示为:

p(y|X,w)=∏i=1NN(yi|wxi,α)" role="presentation">p(y|X,w)=∏i=1NN(yi|wxi,α)p(y|X,w)=∏i=1NN(yi|wxi,α)

最后,利用最大似然估计,可以将上面的表达式转化为一个能量最小的形式。上面是从最大似然估计的角度去求系数。

下面我们考虑从最大后验概率的角度,

p(w|y)=p(y|w)p(w|α)p(α)" role="presentation">p(w|y)=p(y|w)p(w|α)p(α)p(w|y)=p(y|w)p(w|α)p(α)
p(w|α)=N(w|0,α−1I)" role="presentation">p(w|α)=N(w|0,α−1I)p(w|α)=N(w|0,α−1I)

p(α)" role="presentation" style="position: relative;">p(α)p(α) 本身是服从 gamma 分布的。

sklearn 上也给出了一个例子:

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats from sklearn.linear_model import BayesianRidge, LinearRegression # #############################################################################
# Generating simulated data with Gaussian weights
np.random.seed(0)
n_samples, n_features = 100, 100
X = np.random.randn(n_samples, n_features) # Create Gaussian data
# Create weights with a precision lambda_ of 4.
lambda_ = 4.
w = np.zeros(n_features)
# Only keep 10 weights of interest
relevant_features = np.random.randint(0, n_features, 10)
for i in relevant_features:
w[i] = stats.norm.rvs(loc=0, scale=1. / np.sqrt(lambda_))
# Create noise with a precision alpha of 50.
alpha_ = 50.
noise = stats.norm.rvs(loc=0, scale=1. / np.sqrt(alpha_), size=n_samples)
# Create the target
y = np.dot(X, w) + noise # #############################################################################
# Fit the Bayesian Ridge Regression and an OLS for comparison
clf = BayesianRidge(compute_score=True)
clf.fit(X, y) ols = LinearRegression()
ols.fit(X, y) # #############################################################################
# Plot true weights, estimated weights, histogram of the weights, and
# predictions with standard deviations
lw = 2
plt.figure(figsize=(6, 5))
plt.title("Weights of the model")
plt.plot(clf.coef_, color='lightgreen', linewidth=lw,
label="Bayesian Ridge estimate")
plt.plot(w, color='gold', linewidth=lw, label="Ground truth")
plt.plot(ols.coef_, color='navy', linestyle='--', label="OLS estimate")
plt.xlabel("Features")
plt.ylabel("Values of the weights")
plt.legend(loc="best", prop=dict(size=12)) plt.figure(figsize=(6, 5))
plt.title("Histogram of the weights")
plt.hist(clf.coef_, bins=n_features, color='gold', log=True,
edgecolor='black')
plt.scatter(clf.coef_[relevant_features], 5 * np.ones(len(relevant_features)),
color='navy', label="Relevant features")
plt.ylabel("Features")
plt.xlabel("Values of the weights")
plt.legend(loc="upper left") plt.figure(figsize=(6, 5))
plt.title("Marginal log-likelihood")
plt.plot(clf.scores_, color='navy', linewidth=lw)
plt.ylabel("Score")
plt.xlabel("Iterations") # Plotting some predictions for polynomial regression
def f(x, noise_amount):
y = np.sqrt(x) * np.sin(x)
noise = np.random.normal(0, 1, len(x))
return y + noise_amount * noise degree = 10
X = np.linspace(0, 10, 100)
y = f(X, noise_amount=0.1)
clf_poly = BayesianRidge()
clf_poly.fit(np.vander(X, degree), y) X_plot = np.linspace(0, 11, 25)
y_plot = f(X_plot, noise_amount=0)
y_mean, y_std = clf_poly.predict(np.vander(X_plot, degree), return_std=True)
plt.figure(figsize=(6, 5))
plt.errorbar(X_plot, y_mean, y_std, color='navy',
label="Polynomial Bayesian Ridge Regression", linewidth=lw)
plt.plot(X_plot, y_plot, color='gold', linewidth=lw,
label="Ground Truth")
plt.ylabel("Output y")
plt.xlabel("Feature X")
plt.legend(loc="lower left")
plt.show()

scikit-learn 学习笔记-- Generalized Linear Models (三)的更多相关文章

  1. scikit-learn 学习笔记-- Generalized Linear Models (一)

    scikit-learn 是非常优秀的一个有关机器学习的 Python Lib,包含了除深度学习之外的传统机器学习的绝大多数算法,对于了解传统机器学习是一个很不错的平台.每个算法都有相应的例子,既可以 ...

  2. scikit-learn 学习笔记-- Generalized Linear Models (二)

    Lasso regression 今天介绍另外一种带正则项的线性回归, ridge regression 的正则项是二范数,还有另外一种是一范数的,也就是lasso 回归,lasso 回归的正则项是系 ...

  3. Andrew Ng机器学习公开课笔记 -- Generalized Linear Models

    网易公开课,第4课 notes,http://cs229.stanford.edu/notes/cs229-notes1.pdf 前面介绍一个线性回归问题,符合高斯分布 一个分类问题,logstic回 ...

  4. 机器学习-scikit learn学习笔记

    scikit-learn官网:http://scikit-learn.org/stable/ 通常情况下,一个学习问题会包含一组学习样本数据,计算机通过对样本数据的学习,尝试对未知数据进行预测. 学习 ...

  5. [Scikit-learn] 1.1 Generalized Linear Models - from Linear Regression to L1&L2

    Introduction 一.Scikit-learning 广义线性模型 From: http://sklearn.lzjqsdd.com/modules/linear_model.html#ord ...

  6. [Scikit-learn] 1.5 Generalized Linear Models - SGD for Regression

    梯度下降 一.亲手实现“梯度下降” 以下内容其实就是<手动实现简单的梯度下降>. 神经网络的实践笔记,主要包括: Logistic分类函数 反向传播相关内容 Link: http://pe ...

  7. [Scikit-learn] 1.5 Generalized Linear Models - SGD for Classification

    NB: 因为softmax,NN看上去是分类,其实是拟合(回归),拟合最大似然. 多分类参见:[Scikit-learn] 1.1 Generalized Linear Models - Logist ...

  8. [Scikit-learn] 1.1 Generalized Linear Models - Logistic regression & Softmax

    二分类:Logistic regression 多分类:Softmax分类函数 对于损失函数,我们求其最小值, 对于似然函数,我们求其最大值. Logistic是loss function,即: 在逻 ...

  9. 广义线性模型(Generalized Linear Models)

    前面的文章已经介绍了一个回归和一个分类的例子.在逻辑回归模型中我们假设: 在分类问题中我们假设: 他们都是广义线性模型中的一个例子,在理解广义线性模型之前需要先理解指数分布族. 指数分布族(The E ...

随机推荐

  1. Deep Learning(5)

    五.应用实例 1.计算机视觉. ImageNet Classification with Deep Convolutional Neural Networks, Alex Krizhevsky, Il ...

  2. JDK eclipse selenium的安装以及环境变量的配置

    未经允许,禁止转载!!!  未经允许,禁止转载!!! 首先下载安装JDK: 然后双击进行安装 选着第一个:开发工具!点击next 一定要记住:Install to: C:\Program Files\ ...

  3. F题:等差区间(RMQ||线段树)

    原题大意:原题链接  题解链接 给定一个长为n的数组元素和q次区间[l,r]询问,判断区间[l,r]内元素排序后能否构成等差数列 #include<cmath> #include<c ...

  4. Codeforces Round #513 by Barcelona Bootcamp

    A. Phone Numbers 签. #include <bits/stdc++.h> using namespace std; #define N 110 char s[N]; ], ...

  5. Codeforces Round #275 (Div. 2) 题解

    A 题: 说的是在(LR) 之间找出ab互质 bc 互质 ac 不互质的 3个数 数据量小直接暴力 #include <iostream> #include <cstdio> ...

  6. linux下高并发网络应用注意事项

    本文转自:http://www.blogjava.net/bacoo/archive/2012/06/11/380500.html linux下高并发网络应用注意事项 vi /etc/sysctl.c ...

  7. JAVA volatile 解析

    volatile这个关键字可能很多朋友都听说过,或许也都用过.在Java 5之前,它是一个备受争议的关键字,因为在程序中使用它往往会导致出人意料的结果.在Java 5之后,volatile关键字才得以 ...

  8. java读取pdf总结

    第三方软件 1.pdfbox PDFBox 0.7.3.PDFBox是一个开源的对pdf文件进行操作的库. PDFBox-0.7.3.jar加入classpath.同时FontBox1.0.jar加入 ...

  9. poj_3071 Football(概率dp)

    直接上状态转移方程: 记dp[i][j]为第i轮比赛,第j个队伍获胜的概率. 那么初始状态下,dp[0][j]=1://也就是第0轮比赛全都获胜 d[i][j]=sum(d[i-1][j]*d[i-1 ...

  10. 【转载】hibernate缓存机制

    一级缓存(session级别) 我们来看看hibernate提供的一级缓存 //此时会发出一条sql,将所有学生全部查询出来,并放到session的一级缓存当中.当再次查询学生信息时,会首先去缓存中看 ...