Skip to content

Commit

Permalink
Bayesian Linear Regression
Browse files Browse the repository at this point in the history
  • Loading branch information
yuwoliang committed Aug 9, 2017
1 parent d0f342a commit 98d1740
Showing 1 changed file with 186 additions and 0 deletions.
186 changes: 186 additions & 0 deletions Bayesian_Linear_Regression.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Bayesian Linear Regression 贝叶斯线性回归"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Name: [Your name]\n",
"\n",
"Skeleton framework for you to fill in (Code you need to provide is marked by `###`):"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import scipy.io as sio\n",
"import numpy as np \n",
"from numpy.linalg import *\n",
"import pandas as pd"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def BLR_train(Phi, y, beta=100, m_0=None, S_0=None):\n",
" \"\"\"\n",
" Function: Calculate the expectation and covariance of posterior distribution\n",
" Input: \n",
" Phi: Design matrix of training data, size:[number dimension]\n",
" y: Training Label, size: [number 1]\n",
" beta: The precision of Gaussian random variables\n",
" m_0: The mean of conjugate prior distribution, size: [dimension 1]\n",
" s_0: The covariance of conjugate prior distribution, size: [dimension dimension]\n",
" Output: \n",
" m_N: The expectation of posterior distribution\n",
" S_N: The covariance of posterior distribution\n",
" \"\"\"\n",
" m, d = Phi.shape\n",
" if m_0 == None: m_0 = np.zeros((d,1))\n",
" if S_0 == None: S_0 = 0.1*np.eye(d)\n",
" \n",
" # your code\n",
" S_N = ###\n",
" m_N = ###\n",
" \n",
" return m_N, S_N"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def BLR_test(Phi, y, m_N, S_N, beta=100):\n",
" \"\"\"\n",
" Function: Predict the testing data\n",
" Input:\n",
" Phi: Design matrix of testing data\n",
" y: Testing Label\n",
" m_N: The expectation of posterior distribution\n",
" S_N: The covariance of posterior distribution\n",
" beta: The precision of Gaussian random variables\n",
" Output:\n",
" t: Prediction of testing data\n",
" \"\"\"\n",
" # your code\n",
" mu = ###\n",
" var = ###\n",
" \n",
" t = np.sqrt(var) * np.random.randn(y.shape[0], y.shape[1]) + mu\n",
" \n",
" # Three kinds of errors\n",
" er = t - y\n",
" MSE = (er**2).mean() # Mean Squared Error\n",
" MAE = abs(er).mean() # Average Absolute Error\n",
" SD = np.sqrt((( er-er.mean())**2).mean()) # Error Standard Deviation\n",
" \n",
" acc = np.equal(np.rint(t), y).mean() * 100\n",
" text = \"The Linear Regression's accuracy is %.2f%%.\" %(acc)\n",
" print(text)\n",
" \n",
" obj = pd.Series([MSE,MAE,SD], index=['MSE','MAE','SD'])\n",
" print(obj)\n",
" \n",
" return t"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# Import data\n",
"data_path = ### \"The path where you store the SpectralClassification data\" ###\n",
"\n",
"data=sio.loadmat(data_path + \"SpectralClassificationTrain.mat\") \n",
"train_x = data['train_x']\n",
"m, d = train_x.shape\n",
"train_x = np.column_stack( ((np.ones(m)).T , train_x) )\n",
"train_y = np.reshape(data['train_y'][:,0], [-1,1])\n",
"\n",
"data=sio.loadmat(data_path + \"SpectralClassificationTest.mat\") \n",
"test_x = data['test_x']\n",
"m, d = test_x.shape\n",
"test_x = np.column_stack( ((np.ones(m)).T , test_x) )\n",
"test_y = np.reshape(data['test_y'][:,0], [-1,1])\n",
"\n",
"del data"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The Linear Regression's accuracy is 87.44%.\n",
"MSE 0.121337\n",
"MAE 0.291764\n",
"SD 0.348169\n",
"dtype: float64\n"
]
}
],
"source": [
"m_N, S_N = BLR_train(train_x, train_y)\n",
"test_t = BLR_test(train_x, train_y, m_N, S_N)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

0 comments on commit 98d1740

Please sign in to comment.