-
Notifications
You must be signed in to change notification settings - Fork 6
/
spectral_clustering.py
86 lines (66 loc) · 2.78 KB
/
spectral_clustering.py
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
# -*- coding: utf-8 -*-
"""
@author: Makan Arastuie
"""
import numpy as np
from os.path import join
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from scipy.sparse.linalg import svds
from sklearn.preprocessing import normalize
def spectral_cluster(adj, num_classes=2, n_kmeans_init=10, normalize_z=True, verbose=False, plot_eigenvalues=False,
plot_save_path=''):
"""
Runs spectral clustering on weighted or unweighted adjacency matrix
:param adj: weighted, unweighted or regularized adjacency matrix
:param num_classes: number of classes for spectral clustering
:param n_kmeans_init: number of initializations for k-means
:param normalize_z: If True, vector z is normalized to sum to 1
:param verbose: if True, prints the eigenvalues
:param plot_eigenvalues: if True, plots the first `num_classes` singular values
:param plot_save_path: directory to save the plot
:return: predicted clustering membership
"""
# Compute largest num_classes singular values and vectors of adjacency matrix
u, s, v = svds(adj, k=num_classes)
v = v.T
if verbose:
print("Eigenvalues: \n", s)
if plot_eigenvalues:
fig, ax = plt.subplots()
plt.scatter(np.arange(num_classes, 0, -1), s, s=80, marker='*', color='blue')
plt.xlabel('Rank', fontsize=24)
plt.ylabel('Singular Values', fontsize=24)
plt.grid(True)
ax.tick_params(labelsize=20)
plt.tight_layout()
plt.savefig(join(plot_save_path, 'singular_values.pdf'))
plt.show()
# Sort in decreasing order of magnitude
sorted_ind = np.argsort(-s)
u = u[:, sorted_ind]
v = v[:, sorted_ind]
z = np.c_[u, v]
if normalize_z:
z = normalize(z, norm='l2', axis=1)
km = KMeans(n_clusters=num_classes, n_init=n_kmeans_init)
cluster_pred = km.fit_predict(z)
return cluster_pred
def regularized_spectral_cluster(adj, num_classes=2, tau=None, n_kmeans_init=10, normalize_z=True):
"""
Runs regularized spectral clustering on weighted or unweighted adjacency matrix
:param adj: weighted, unweighted or regularized adjacency matrix
:param num_classes: number of classes for spectral clustering
:param tau: regularization parameter
:param n_kmeans_init: number of initializations for k-means
:param normalize_z: If True, vector z is normalized to sum to 1
:return: predicted clustering membership
"""
node_outdegree = np.sum(adj, axis=1)
node_indegree = np.sum(adj, axis=0)
if tau is None:
tau = np.mean(node_outdegree)
o_t = np.diag(1 / np.sqrt(node_outdegree + tau))
p_t = np.diag(1 / np.sqrt(node_indegree + tau))
l_t = o_t.dot(adj).dot(p_t)
return spectral_cluster(l_t, num_classes, n_kmeans_init, normalize_z)