-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathslides.html
445 lines (307 loc) · 11.5 KB
/
slides.html
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
<!DOCTYPE html>
<html>
<head>
<title>NN</title>
<meta charset="utf-8">
<link rel="stylesheet" href="https://unpkg.com/purecss@1.0.1/build/pure-min.css" integrity="sha384-oAOxQR6DkCoMliIh8yFnu25d7Eq/PHS21PClpwjOTeU2jRSq11vu66rf90/cZr47" crossorigin="anonymous"> <style>
@import url(https://fonts.googleapis.com/css?family=Yanone+Kaffeesatz);
@import url(https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic);
@import url(https://fonts.googleapis.com/css?family=Ubuntu+Mono:400,700,400italic);
body { font-family: 'Droid Serif'; }
h1, h2, h3 {
font-family: 'Yanone Kaffeesatz';
font-weight: normal;
}
.remark-code, .remark-inline-code { font-family: 'Ubuntu Mono'; }
.reference{
font-size: 10px;
}
.smaller-font { font-size:14px }
@page {
size: 908px 681px;
margin: 0;
}
@media print {
.remark-slide-scaler {
width: 100% !important;
height: 100% !important;
transform: scale(1) !important;
top: 0 !important;
left: 0 !important;
}
}
.green {
color: #45ADA8;
}
.figure img{
height: 550px;
}
.figure-200 img{
height: 200px;
}
.figure-250 img{
height: 250px;
}
.figure-300 img{
height: 300px;
}
.figure-350 img{
height: 350px;
}
.figure-w500 img{
width: 500px;
}
.figure-w600 img{
width: 600px;
}
</style>
</head>
<body>
<textarea id="source">
class: center, middle
# Nearest Neighbor
CS534 - Machine Learning
Yubin Park, PhD
---
class: center, middle
Consider
$$ y_1 = f(\mathbf{x}_1) $$
and
$$ y_2 = f(\mathbf{x}_2) $$
---
class: center, middle
If
$$ \mathbf{x}_1 = \mathbf{x}_2 $$
then
$$ y_1 = y_2 $$
---
class: center, middle
What if
$$ \mathbf{x}_1 \approx \mathbf{x}_2 $$
then
$$ y_1 \approx y_2 \text{?}$$
---
## Distance Metric
We need to "measure" how similar `\(\mathbf{x}_1\)` and `\(\mathbf{x}_2\)` are using a distance function.
A distance function satisfies:
1. `\(d(\mathbf{x}_1, \mathbf{x}_2) \ge 0\)`, and `\(d(\mathbf{x}_1, \mathbf{x}_2) = 0\)` if and only if `\(\mathbf{x}_1=\mathbf{x}_2\)`
1. `\(d(\mathbf{x}_1, \mathbf{x}_2) = d(\mathbf{x}_2, \mathbf{x}_1)\)` (symmetric)
1. `\(d(\mathbf{x}_1, \mathbf{x}_2) \le d(\mathbf{x}_1, \mathbf{x}_3) + d(\mathbf{x}_3, \mathbf{x}_2)\)` (triangle inequality)
Questions:
- Is `\( (\mathbf{x}_1 - \mathbf{x}_2 )^T(\mathbf{x}_1 - \mathbf{x}_2 ) \)` a distance function?
- How about `\(\frac{\mathbf{x}_1^T \mathbf{x}_2}{\|\mathbf{x}_1\| \|\mathbf{x}_2\|}\)` ([cosine similarity](https://en.wikipedia.org/wiki/Cosine_similarity))?
- How about `\(1 - \frac{\mathbf{x}_1^T \mathbf{x}_2}{\|\mathbf{x}_1\| \| \mathbf{x}_2\|}\)` (1 - cosine similarity)?
---
## k-Nearest Neighbors (kNN)
No training is needed for kNN.
For a new data point `\(\mathbf{x}_{\text{new}}\)`,
1. For `\(i=0\)` to `\(n\)`,
1. Measure the distance between `\(\mathbf{x}_{\text{new}}\)` and `\(\mathbf{x}_{i}\)`
1. Select Top-k nearest neighbors
1. `\(\hat{y} = \frac{\sum \mathbf{x}_{nn}}{k}\)`
kNN is an [instance-based learning](https://en.wikipedia.org/wiki/Instance-based_learning) (or memory-based learning).
Question:
- What is the effect of `\(k\)` on the bias and variance of the model?
---
class: center, middle
.figure-w500[![nn1](img/nn1.png)]
.reference[Chapter 13 of [ESLII](https://web.stanford.edu/~hastie/ElemStatLearn/)]
---
class: center, middle
.figure-w500[![nn1](img/nn1b.png)]
.reference[Chapter 13 of [ESLII](https://web.stanford.edu/~hastie/ElemStatLearn/)]
---
class: center, middle
.figure-w500[![nn1](img/nn2b.png)]
.reference[Chapter 13 of [ESLII](https://web.stanford.edu/~hastie/ElemStatLearn/)]
---
class: center, middle
.figure-w500[![nn1](img/nn2.png)]
.reference[Chapter 13 of [ESLII](https://web.stanford.edu/~hastie/ElemStatLearn/)]
---
## Practical Considerations
- Slow Preciction Speed
- You need to scan all data points in the training set, `\(O(n)\)`
- => [Approximate Nearest Neighbors](https://en.wikipedia.org/wiki/Nearest_neighbor_search#Approximate_nearest_neighbor)
- Ambiguity of Metric
- Which distance function should I choose?
- => [Metric Learning](https://en.wikipedia.org/wiki/Similarity_learning)
- Curse of dimensionality
- Distances between sample pairs are about the same in high dimensional spaces
- => [Dimensionality Reduction](https://en.wikipedia.org/wiki/Dimensionality_reduction)
---
## Approximate Nearest Neighbor
We can make kNN a lot faster if we allow some mistakes.
i.e. we will find `\(k\)` **near** neighbors, not the exact Top-k nearest neighbors.
Hence, this algorithm is called Approximate Nereast Neighbors (ANN).
The main technique is [Locality-sensitive Hashing](https://en.wikipedia.org/wiki/Locality-sensitive_hashing) (LSH).
Simply speaking,
1. We want to have a function (LSH) that puts similar items to the same bucket with a high probability
1. For a new data point, we apply the function and finds the bucket that have similar data points to the data point
1. Find Top-k within the bucket
Of course, there will be some False Positives and False Negatives...
---
## LSH Basic (1)
Let's start with the cosine disimilarity:
$$ d(\mathbf{x}_1, \mathbf{x}_2) = 1 - \frac{\mathbf{x}_1^T \mathbf{x}_2}{\lVert\mathbf{x}_1\rVert \lVert \mathbf{x}_2\rVert} $$
With a random vector `\(\mathbf{u}\)`, we will make a hash function as follows:
$$ h_{\mathbf{u}}(\mathbf{x}) = \text{sign}(\mathbf{x}^T\mathbf{u})$$
In other words, the hash function returns either 1 or -1 (or 0) depending on the angle between `\(\mathbf{x}\)` and `\(\mathbf{u}\)`. Then, we have:
$$ \text{Pr}(h\_{\mathbf{u}}(\mathbf{x}\_1)=h\_{\mathbf{u}}(\mathbf{x}\_2)) = 1 - \frac{\theta(\mathbf{x}_1, \mathbf{x}_2)}{\pi} \approx \cos(\theta(\mathbf{x}_1, \mathbf{x}_2)) $$
The probability of having the same hash value approximates their cosine similariity. This [random projection](https://en.wikipedia.org/wiki/Random_projection) hash is called [SimHash](https://en.wikipedia.org/wiki/SimHash).
---
## LSH Basic (2)
Under SimHash, two items will be put in the same bucket if they are similar.
More precisely, the more simialar those two are, the more likely they will be put in the same bucket.
We have made 2 buckets using 1 SimHash. Are 2 buckets enough?
To make `\(2^R\)` buckets, we use `\(R\)` random vectors: `\(\mathbf{u}_1, \mathbf{u}_2, \ldots, \mathbf{u}_R\)`.
$$ h\_{\mathbf{U}} = (h\_{\mathbf{u}\_1}, h\_{\mathbf{u}\_2}, \ldots, h\_{\mathbf{u}\_R}) $$
```python
def simhash(x, U):
"""Returns an R length binary hash value."""
# x: a vector (m x 1)
# U: a matrix (m x R)
return "".join([str(int(h>0)) for h in np.dot(x, U)])
```
---
## LSH Basic (3)
Then, the probability of two data points ending up in the same bucket is:
$$ \text{Pr}(h\_{\mathbf{U}}(\mathbf{x}\_1)=h\_{\mathbf{U}}(\mathbf{x}\_2)) = s(\mathbf{x}_1, \mathbf{x}_2)^R $$
where `\(s(\mathbf{x}_1, \mathbf{x}_2)\)` represents the similarity between two points.
And the probability that two data points will be put in different buckets:
$$ \text{Pr}(h\_{\mathbf{U}}(\mathbf{x}\_1) \neq h\_{\mathbf{U}}(\mathbf{x}\_2)) = 1 - s(\mathbf{x}_1, \mathbf{x}_2)^R$$
Now, we have enough buckets to separate disimilar points.
However, we have a new challenge.
For a new data point, what if its corresponding bucket is empty?
Or, even if it is not empty, but full of irrelevant data points?
---
## LSH Basic (4)
Let's make multiple hash functions, `\(h_{\mathbf{U}_1}, h_{\mathbf{U}_2}, \ldots, h_{\mathbf{U}_B}\)`, and hope that at least one matched bucket is not empty.
Since
$$ \text{Pr}(h\_{\mathbf{U}}(\mathbf{x}\_1) \neq h\_{\mathbf{U}}(\mathbf{x}\_2)) = 1 - s(\mathbf{x}_1, \mathbf{x}_2)^R $$
we have:
$$ \text{Pr}(h\_{\mathbf{U}\_b}(\mathbf{x}\_1) \neq h\_{\mathbf{U}\_b}(\mathbf{x}\_2), \forall b \in 1, \dots, B) = (1 - s(\mathbf{x}_1, \mathbf{x}_2)^R)^B $$
In other words, the probability of finding at least one bucket that has a neighbor candidate `\( \mathbf{x}_{\text{neighbor}}\)` with `\(s(\mathbf{x}_{\text{new}}, \mathbf{x}_{\text{neighbor}})\)`:
$$ \text{Pr}(\text{hit}) = 1 - (1 - s(\mathbf{x}\_{\text{new}}, \mathbf{x}\_{\text{neighbor}})^R)^B $$
---
## LSH Basic (5)
Why are we doing this?
So that we can find neighbors that are `\(s(\mathbf{x}_{\text{new}}, \mathbf{x}_{\text{neighbor}}) > t\)` with a very high probability.
.center[.figure-350[![amplifier](img/lshamp.png)]]
---
## LSH Toy Example (1)
```python
R = 20
B = 5
def simhash(x, U):
return "".join([str(int(h>0)) for h in np.dot(x, U)])
```
```python
def fit(X, y, U_lst):
n, m = X.shape
B = len(U_lst)
htab = [defaultdict(list) for b in range(B)]
for i in range(n):
x_i = X[i,:]
y_i = y[i]
for b in range(B):
key = simhash(x_i, U_lst[b])
htab[b][key].append((x_i, y_i))
return htab
```
---
## LSH Toy Example (2)
```python
def predict(X, U_lst, htab):
y_hat = []
n, m = X.shape
B = len(U_lst)
for i in range(n):
x_i = X[i,:]
y_hat_i = 0.0
for b in range(B):
key = simhash(x_i, U_lst[b])
if key not in htab[b]:
continue
pairs = htab[b][key]
X_nn = np.array([p[0] for p in pairs])
idx = np.argsort(np.dot(X_nn, x_i))[-1]
y_hat_i = [p[1] for p in pairs][idx]
break
y_hat.append(y_hat_i)
return y_hat
```
---
## LSH Toy Example (3)
```python
data = load_iris()
scaler = StandardScaler()
X = data.data
y = (data.target == 1).astype(int)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
n, m = X.shape
U_lst = [np.random.randn(m, R) for b in range(B)]
htab = fit(X_train, y_train, U_lst)
y_hat = predict(X_test, U_lst, htab)
acc = np.mean(y_hat == y_test)
print(acc)
```
```bash
$ python lsh.py
0.9
```
---
class: center, middle
## Questions?
</textarea>
<script src="https://remarkjs.com/downloads/remark-latest.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS_HTML&delayStartupUntil=configured" type="text/javascript">
</script>
<script type="text/javascript">
var hljs = remark.highlighter.engine;
/*
Language: terminal console
Author: Josh Bode <joshbode@gmail.com>
*/
hljs.registerLanguage('terminal', function() {
return {
contains: [
{
className: 'string',
begin: '^([\\w.]+)@([\\w.]+)'
},
{
className: 'constant',
begin: ' (.*) \\$ '
},
{
className: 'ansi',
begin: '<span style\\="([^"]+)">',
end: '<\\/span>'
}
]
}
});
var slideshow = remark.create({
highlightStyle: 'monokai'
});
// extract the embedded styling from ansi spans
var highlighted = document.querySelectorAll("code.terminal span.hljs-ansi");
Array.prototype.forEach.call(highlighted, function(next) {
next.insertAdjacentHTML("beforebegin", next.textContent);
next.parentNode.removeChild(next);
});
// Setup MathJax
MathJax.Hub.Config({
tex2jax: {
skipTags: ['script', 'noscript', 'style', 'textarea', 'pre']
}
});
MathJax.Hub.Configured();
</script>
</body>
</html>