/
naive_bayes.ipynb
291 lines (291 loc) · 9.98 KB
/
naive_bayes.ipynb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Naive Bayes"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### by Chiyuan Zhang"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This notebook illustrates <a href=\"http://en.wikipedia.org/wiki/Multiclass_classification\">multiclass</a> learning using <a href=\"http://en.wikipedia.org/wiki/Naive_Bayes_classifier\">Naive Bayes</a> in Shogun. A semi-formal introduction to <a href=\"http://en.wikipedia.org/wiki/Logistic_regression\">Logistic Regression</a> is provided at the end."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"$$\n",
"P\\left( Y=k | X = x \\right) = \\frac{P(X=x|Y=k)P(Y=k)}{P(X=x)}\n",
"$$\n",
"\n",
"The prediction is then made by\n",
"\n",
"$$\n",
"y = \\operatorname*{argmax}_{k\\in\\{1,\\ldots,K\\}}\\; P(Y=k|X=x)\n",
"$$\n",
"\n",
"Since $P(X=x)$ is a constant factor for all $P(Y=k|X=x)$, $k=1,\\ldots,K$, there\n",
"is no need to compute it."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In `SHOGUN`, [GaussianNaiveBayes](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1GaussianNaiveBayes.html) implements the Naive Bayes\n",
"algorithm. It is prefixed with \"Gaussian\" because the probability model for\n",
"$P(X=x|Y=k)$ for each $k$ is taken to be a multi-variate Gaussian distribution.\n",
"Furthermore, each dimension of the feature vector $X$ is assumed to be\n",
"independent. The *Naive* independence assumption enables us the learn the\n",
"model by estimating the parameters for each feature dimension independently,\n",
"thus the whole learning algorithm runs very quickly. And this is also the \n",
"reason for its name. However, this assumption can be very restrictive. In\n",
"this demo, we show a simple 2D example. There are 3 linearly\n",
"separable classes. The scattered points are training samples with colors\n",
"indicating their labels. The filled area indicate the hypothesis learned by\n",
"the [GaussianNaiveBayes](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1GaussianNaiveBayes.html). The training samples are actually\n",
"generated from three Gaussian distributions. But since the covariance for those\n",
"Gaussian distributions are not diagonal (i.e. there are *rotations*), the GNB\n",
"algorithm cannot handle them properly.\n",
"\n",
"We first init the models for generating samples for this demo:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import shogun as sg\n",
"\n",
"%matplotlib inline\n",
"\n",
"np.random.seed(0)\n",
"\n",
"n_train = 300\n",
"\n",
"models = [{'mu': [8, 0], 'sigma':\n",
" np.array([[np.cos(-np.pi/4),-np.sin(-np.pi/4)],\n",
" [np.sin(-np.pi/4), np.cos(-np.pi/4)]]).dot(np.diag([1,4]))},\n",
" {'mu': [0, 0], 'sigma':\n",
" np.array([[np.cos(-np.pi/4),-np.sin(-np.pi/4)],\n",
" [np.sin(-np.pi/4), np.cos(-np.pi/4)]]).dot(np.diag([1,4]))},\n",
" {'mu': [-8,0], 'sigma':\n",
" np.array([[np.cos(-np.pi/4),-np.sin(-np.pi/4)],\n",
" [np.sin(-np.pi/4), np.cos(-np.pi/4)]]).dot(np.diag([1,4]))}]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A helper function is defined to generate samples:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def gen_samples(n_samples):\n",
" X_all = np.zeros((2, 0))\n",
" Y_all = np.zeros(0)\n",
"\n",
" for i, model in enumerate(models):\n",
" Y = np.zeros(n_samples) + i+1\n",
" X = np.array(model['sigma']).dot(np.random.randn(2, n_samples)) + np.array(model['mu']).reshape((2,1))\n",
"\n",
" X_all = np.hstack((X_all, X))\n",
" Y_all = np.hstack((Y_all, Y))\n",
"\n",
" return (X_all, Y_all)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Then we train the GNB model with `SHOGUN`:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"X_train, Y_train = gen_samples(n_train)\n",
"\n",
"machine = sg.create_machine(\"GaussianNaiveBayes\", labels=sg.create_labels(Y_train))\n",
"\n",
"machine.train(sg.create_features(X_train))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Run classification over the whole area to generate color regions:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"delta = 0.1\n",
"x = np.arange(-20, 20, delta)\n",
"y = np.arange(-20, 20, delta)\n",
"X,Y = np.meshgrid(x,y)\n",
"Z = machine.apply(sg.create_features(np.vstack((X.flatten(), Y.flatten())))).get(\"labels\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Plot figure:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(8,5))\n",
"plt.contourf(X, Y, Z.reshape(X.shape), np.arange(0, len(models)+1))\n",
"plt.scatter(X_train[0,:],X_train[1,:], c=Y_train)\n",
"plt.axis('off')\n",
"plt.tight_layout()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Although the independent assumption is usually considered to be too optimistic \n",
"in reality, Naive Bayes sometimes works very well in some applications. For \n",
"example, in email spam filtering, Naive Bayes (More specifically, the \n",
" discrete Naive Bayes is generally used in this scenario. The main \n",
" difference with Gaussian Naive Bayes is that a tabular instead of a \n",
" parametric Gaussian distribution is used to describe the likelihood \n",
" $P(X=x|K=k)$) is a very popular and widely used method."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This algorithm is closely related to the *Gaussian Mixture Model* (GMM) learning\n",
"algorithm. However, while GMM is an unsupervised learning algorithm, Gaussian\n",
"Naive Bayes is supervised learning. It uses the training labels to directly\n",
"estimate the Gaussian parameters for each class, thus avoids the iterative\n",
"*Expectation Maximization* procedures in GMM.\n",
"\n",
"The merit of GNB is that both training and predicting are very fast, and it has\n",
"no hyper-parameters."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Brief Introduction to Logistic Regression\n",
"\n",
"Although named logistic *regression*, it is actually a classification\n",
"algorithm. Similar to *Naive Bayes*, logistic regression computes the\n",
"posterior $P(Y=k|X=x)$ and makes prediction by\n",
"\n",
"$$\n",
"y = \\operatorname*{argmax}_{k\\in\\{1,\\ldots,K\\}}\\; P(Y=k|X=x)\n",
"$$\n",
"\n",
"However, Naive Bayes is a *generative model*, in which the distribution of\n",
"the input variable $X$ is also modeled (by a Gaussian distribution in this\n",
"case). But logistic regression is a *discriminative model*, which doesn't\n",
"care about the distribution of $X$, and models the posterior directly.\n",
"Actually, the two algorithms are a *generative-discriminative pair*. \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To be specific, logistic regression uses *linear* functions in $X$ to model the\n",
"posterior probabilities:\n",
"\n",
"\n",
"\\begin{eqnarray}\n",
" \\log\\frac{P(Y=1|X=x)}{P(Y=K|X=x)} &=& \\beta_{10} + \\beta_1^Tx \\\\\\\\\n",
" \\log\\frac{P(Y=2|X=x)}{P(Y=K|X=x)} &=& \\beta_{20} + \\beta_2^Tx \\\\\\\\\n",
" &\\vdots& \\nonumber\\\\\\\\\n",
" \\log\\frac{P(Y=K-1|X=x)}{P(Y=K|X=x)} &=& \\beta_{(K-1)0} + \\beta_{K-1}^Tx\n",
"\\end{eqnarray}\n",
"\n",
"\n",
"The training of a logistic regression model is carried out via *maximum\n",
" likelihood estimation* of the parameters\n",
"$\\boldsymbol\\beta = \\{\\beta_{10},\\beta_1^T,\\ldots,\\beta_{(K-1)0},\\beta_{K-1}^T\\}$. There is no\n",
"closed form solution for the estimated parameters.\n",
"\n",
"There is no independent implementation of logistic regression in `SHOGUN`, \n",
"but the `LibLinear` becomes a logistic regression model when\n",
"constructed with the argument `L2R_LR`. This model also include a\n",
"regularization term of the $\\ell_2$-norm of $\\boldsymbol\\beta$. If sparsity in\n",
"$\\boldsymbol\\beta$ is needed, one can also use `L1R_LR`, which replaces\n",
"the $\\ell_2$-norm regularizer with a $\\ell_1$-norm regularizer.\n",
"\n",
"Unfortunately, while the original LibLinear implementation of Logistic Regression support multiclass case, due to interface incompatability, one cannot use LibLinear as a multiclass-machine in `SHOGUN` directly so far. An easy work-around is to use multiclass-to-binary reduction instead. Please see the Multiclass Reduction tutorial for details."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"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.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 1
}