-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlle.py
More file actions
73 lines (59 loc) · 2.14 KB
/
lle.py
File metadata and controls
73 lines (59 loc) · 2.14 KB
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
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import time
import numpy
import scipy, scipy.linalg, scipy.sparse, scipy.sparse.linalg
from l2_distance import *
def lle(src, dim = 2, k = 10, verbose = True, debug = False):
start = time.time()
if verbose:
print("LLE running on %d points in %d dimensions" % src.shape)
# STEP1: Compute pairwise distances & Find neighbors
if verbose:
print("Finding %d nearest neighbors..." % k)
dist = l2_distance(src, src)
cpdist = numpy.array([])
if debug:
cpdist = dist.copy()
rn = xrange(dist.shape[0])
dist[rn, rn] = numpy.inf
neighborhood = dist.argsort(1)
# STEP2: Solve for Reconstruction Weights
tol = 0
if k > dim:
tol = 1e-3
if verbose:
print("Solving for reconstruction weights...")
W = numpy.zeros((src.shape[0], k))
for i in xrange(W.shape[0]):
z = src[neighborhood[i, :k], :] - src[i]
C = numpy.dot(z, z.T)
C = C + numpy.eye(k) * tol * numpy.trace(C)
W[i, :] = scipy.linalg.solve(C, numpy.ones((k, 1))).T
W[i, :] = W[i, :] / W[i, :].sum()
# STEP3: Compute Embedding from Eigenvects of Cost Matrix M = (1 - W).T (1 - W)
# M = scipy.sparse.csc_matrix(numpy.eye(src.shape[0]))
if verbose:
print("Computing embedding...")
M = numpy.eye(src.shape[0])
for i in xrange(M.shape[0]):
w = W[i, :]
j = neighborhood[i, :k]
M[i, j] = M[i, j] - w
M[j, i] = M[j, i] - w
for l in xrange(w.shape[0]):
M[j[l], j] = M[j[l], j] + w[l] * w
# Calculation of Embedding
val, vec = scipy.linalg.eig(M)
index = numpy.real(val).argsort()
index = index[::-1]
end = time.time()
if verbose:
print("Elapsed time... %f" % (end - start))
if debug:
debuginfo = {"distance_matrix" : cpdist, "reconst_weight" : W, \
"cost_matrix" : M, "eigval" : val, "eigvec" : vec}
return (numpy.real(vec)[:, index[-(dim + 1):-1]] * numpy.sqrt(src.shape[0]), \
debuginfo)
else:
return numpy.real(vec)[:, index[-(dim + 1):-1]] * numpy.sqrt(src.shape[0])