# 拉普拉斯特征图降维及其python实现

## 1、python实现拉普拉斯降维

[python] view plain
1. def laplaEigen(dataMat,k,t):
2.     m,n=shape(dataMat)
3.     W=mat(zeros([m,m]))
4.     D=mat(zeros([m,m]))
5.     for i in range(m):
6.         k_index=knn(dataMat[i,:],dataMat,k)
7.         for j in range(k):
8.             sqDiffVector = dataMat[i,:]-dataMat[k_index[j],:]
9.             sqDiffVector=array(sqDiffVector)**2
10.             sqDistances = sqDiffVector.sum()
11.             W[i,k_index[j]]=math.exp(-sqDistances/t)
12.             D[i,i]+=W[i,k_index[j]]
13.     L=D-W
14.     Dinv=np.linalg.inv(D)
15.     X=np.dot(D.I,L)
16.     lamda,f=np.linalg.eig(X)
17. return lamda,f
18. def knn(inX, dataSet, k):
19.     dataSetSize = dataSet.shape[0]
20.     diffMat = tile(inX, (dataSetSize,1)) - dataSet
21.     sqDiffMat = array(diffMat)**2
22.     sqDistances = sqDiffMat.sum(axis=1)
23.     distances = sqDistances**0.5
24.     sortedDistIndicies = distances.argsort()
25. return sortedDistIndicies[0:k]
26. dataMat, color = make_swiss_roll(n_samples=2000)
27. lamda,f=laplaEigen(dataMat,11,5.0)
28. fm,fn =shape(f)
29. print 'fm,fn:',fm,fn
30. lamdaIndicies = argsort(lamda)
31. first=0
32. second=0
33. print lamdaIndicies[0], lamdaIndicies[1]
34. for i in range(fm):
35.     if lamda[lamdaIndicies[i]].real>1e-5:
36.         print lamda[lamdaIndicies[i]]
37.         first=lamdaIndicies[i]
38.         second=lamdaIndicies[i+1]
39.         break
40. print first, second
41. redEigVects = f[:,lamdaIndicies]
42. fig=plt.figure('origin')
44. ax1.scatter(dataMat[:, 0], dataMat[:, 1], dataMat[:, 2], c=color,cmap=plt.cm.Spectral)
45. fig=plt.figure('lowdata')
47. ax2.scatter(f[:,first], f[:,second], c=color, cmap=plt.cm.Spectral)
48. plt.show()

## 2、拉普拉斯降维实验

[python] view plain
1. def make_swiss_roll(n_samples=100, noise=0.0, random_state=None):
2.     #Generate a swiss roll dataset.
3.     t = 1.5 * np.pi * (1 + 2 * random.rand(1, n_samples))
4.     x = t * np.cos(t)
5.     y = 83 * random.rand(1, n_samples)
6.     z = t * np.sin(t)
7.     X = np.concatenate((x, y, z))
8.     X += noise * random.randn(3, n_samples)
9.     X = X.T
10.     t = np.squeeze(t)
11. return X, t

N=5t=15             N=7t=15            N=9t=15

N=11t=15             N=13t=15            N=15t=15

N=17t=15             N=19t=15            N=21t=15

N=23t=15             N=25t=15            N=27t=15

N=29t=15             N=31t=15            N=33t=15

N=25t=5              N=25t=8           N=25t=10

N=25t=12            N=25t=14               N=25t=50

N=25t=Inf