Turn: Complete simplest spectral clustering Python code

Source: Internet
Author: User

http://blog.csdn.net/waleking/article/details/7584084

Spectral clustering is done for Karate_club datasets. Because it is 2-way clustering, relatively simple, got the new representation space of the diagram, did not do K-means, only for the normalized Laplace matrix of the second eigenvalue to do a symbolic judgment, which and spectral clustering Tutorial The description in the article is consistent.

Reference to NumPy scipy matplotlib NETWORKX Package

  1. #coding =utf-8
  2. #MSC means multiple spectral clustering
  3. import NumPy as NP
  4. import scipy as sp
  5. import scipy.linalg as linalg
  6. import Networkx as NX
  7. import Matplotlib.pyplot as plt
  8. def Getnormlaplacian(W):
  9. "" " Input matrix w= (W_IJ)
  10. "Compute d=diag (D1,... DN)
  11. "and L=d-w
  12. "and lbar=d^ ( -1/2) ld^ ( -1/2)
  13. "Return Lbar
  14. """
  15. D=[np.sum (Row) for row in W]
  16. D=np.diag (d)
  17. L=d-w
  18. #Dn =d^ ( -1/2)
  19. Dn=np.power (Np.linalg.matrix_power (D,-1),0.5)
  20. Lbar=np.dot (Np.dot (dn,l), Dn)
  21. return Lbar
  22. def Getksmallesteigvec(lbar,k):
  23. "" "input
  24. "Matrix Lbar and K
  25. "Return
  26. "K smallest eigen values and their corresponding eigen vectors
  27. """
  28. Eigval,eigvec=linalg.eig (Lbar)
  29. Dim=len (Eigval)
  30. #查找前k小的eigval
  31. Dicteigval=dict (Zip (Eigval,range (0,dim)))
  32. Keig=np.sort (eigval) [0:k]
  33. Ix=[dicteigval[k] for K in Keig]
  34. return Eigval[ix],eigvec[:,ix]
  35. def checkresult(lbar,eigvec,eigval,k):
  36. """
  37. the input
  38. "Matrix Lbar and K Eig values and K Eig vectors
  39. "Print norm (Lbar*eigvec[:,i]-lamda[i]*eigvec[:,i])
  40. """
  41. Check=[np.dot (Lbar,eigvec[:,i])-eigval[i]*eigvec[:,i] for i in range (0,k)]
  42. Length=[np.linalg.norm (e) for E in check]/np.spacing (1)
  43. Print ("lbar*v-lamda*v is%s*%s"% (length,np.spacing (1)))
  44. G=nx.karate_club_graph ()
  45. Nodenum=len (G.nodes ())
  46. M=nx.to_numpy_matrix (g)
  47. Lbar=getnormlaplacian (M)
  48. k=2
  49. Keigval,keigvec=getksmallesteigvec (Lbar,k)
  50. Print ("K Eig Val is%s"% keigval)
  51. Print ("K Eig Vec is%s"% Keigvec)
  52. Checkresult (Lbar,keigvec,keigval,k)
  53. #跳过k means, using the simplest symbolic discriminant method to find the point of attribution
  54. Clustera=[i for I in range (0,nodenum) if keigvec[i,1]>0]
  55. Clusterb=[i for I in range (0,nodenum) if keigvec[i,1]<0]
  56. #draw Graph
  57. Collist=dict.fromkeys (G.nodes ())
  58. For Node,score in collist.items ():
  59. if node in clustera:
  60. collist[node]=0
  61. Else:
  62. collist[node]=0.6
  63. Plt.figure (figsize= (8,8))
  64. Pos=nx.spring_layout (g)
  65. Nx.draw_networkx_edges (g,pos,alpha=0.4)
  66. Nx.draw_networkx_nodes (G,pos,nodelist=collist.keys (),
  67. Node_color=collist.values (),
  68. Cmap=plt.cm.reds_r)
  69. Nx.draw_networkx_labels (g,pos,font_size=10,font_family=' Sans-serif ')
  70. Plt.axis (' off ')
  71. Plt.title ("Karate_club spectral Clustering")
  72. Plt.savefig ("Spectral_clustering_result.png")
  73. Plt.show ()


Resulting cluster results:

Thanks to the Python community!

Life was short, use python!

Turn: Complete simplest spectral clustering Python code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.