In [176]:
import numpy as np
import pandas as pd
import scipy as sp
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import MinMaxScaler
import networkx as nx
from sklearn.cluster import KMeans
%matplotlib inline
In [205]:
G=nx.karate_club_graph()
G = nx.Graph(G)
print len(G.nodes())
In [85]:
degree_sequence=sorted(nx.degree(G).values(),reverse=True) # degree sequence
dmax=max(degree_sequence)
print dmax
Computing the k-core decomposition of a graph
In [86]:
core_dec = nx.core_number(G)
print core_dec
Plotting the graph; nodes with the same color belong in the same core
In [120]:
colors = ['#d7191c', '#fdae61', '#ffffbf', '#abdda4', '#2b83ba']
node_colors = [ colors[core_dec[v]] for v in G.nodes()]
nx.draw(G, node_color=node_colors, with_labels=True)
In [206]:
cut_edges = nx.minimum_edge_cut(G)
print cut_edges
In [207]:
Gcopy = G.copy()
Gcopy.remove_edges_from(cut_edges)
In [208]:
cc = nx.connected_components(Gcopy)
node_set = {}
i = 1
for s in cc:
for node in s:
node_set[node] = i
i+=1
print node_set
In [209]:
colors = ['#d7191c', '#2b83ba']
node_colors = [ colors[node_set[v]-1] for v in G.nodes()]
nx.draw(G, node_color=node_colors, with_labels='True')
In [210]:
cut_edges = nx.minimum_edge_cut(G, s=0, t=33)
print cut_edges
In [211]:
Gcopy = G.copy()
Gcopy.remove_edges_from(cut_edges)
In [212]:
cc = nx.connected_components(Gcopy)
node_set = {}
for i, s in enumerate(cc):
for node in s:
node_set[node] = i
colors = ['#d7191c', '#2b83ba']
node_colors = [ colors[node_set[v]-1] for v in G.nodes()]
nx.draw(G, node_color=node_colors, with_labels='True')
In [213]:
G=nx.karate_club_graph()
G = nx.Graph(G)
In [214]:
f = nx.fiedler_vector(G)
print f
In [215]:
s = np.zeros(len(f))
s[f>0]=1
s = s.astype(int)
#s = s.tolist()
print s, type(s)
In [216]:
colors = ['#d7191c', '#2b83ba']
node_colors = [ colors[s[v]] for v in G.nodes()]
node_colors = ['#d7191c' if f[i] < 0 else '#2b83ba' for i, v in enumerate(G.nodes())]
nx.draw(G, node_color=node_colors, with_labels='True')
In [182]:
from numpy.random import RandomState
def generate_noisy_subcliques(nodes_per_clique, inside_p, across_p, min_node_label=0, seed=None):
"""Generates a graph which consists of small cliques connected with each other.
The noise within a clique and across cliques can be set by the `inside_p` and
`across_p` parameters respectively.
Parameters
----------
nodes_per_clique : list
The size of this list corresponds to the number of cliques that will be
generated. The value of each element will be the size of the corresponding
clique.
inside_p : float
The probability of an edge inside a clique. The higher this number, the more
each clique will resemble a fully connected graph.
across_p : float
The probability of an edge across cliques.
min_node_label : int, default is 0
The minimum node label of the graph.
seed : int, default is None
The seed to the pseudorandom number generator.
Returns
-------
G : networkX graph
The generated graph.
"""
prng = RandomState(seed)
clique_list = []
number_of_cliques = len(nodes_per_clique)
# Make the independent cliques
starting_node = min_node_label
for clique in range(number_of_cliques):
G = nx.Graph()
for u in range(starting_node, starting_node + nodes_per_clique[clique]):
for v in range(u + 1, starting_node + nodes_per_clique[clique]):
if prng.rand() < inside_p:
G.add_edge(u, v)
clique_list.append(G)
starting_node += nodes_per_clique[clique]
# Combine them in one graph
G = nx.Graph()
for clique in range(number_of_cliques):
G.add_edges_from(clique_list[clique].edges())
# Connect edges across the cliques
for i in range(number_of_cliques):
clique_from = clique_list[i]
for j in range(i + 1, number_of_cliques):
clique_to = clique_list[j]
for u in clique_from.nodes():
for v in clique_to.nodes():
if prng.rand() < across_p:
G.add_edge(u, v)
return G
In [217]:
nodes_per_clique = [10, 10, 10]
across_p = 0.05
inside_p = 0.9
cliques = generate_noisy_subcliques(nodes_per_clique, inside_p, across_p)
nx.draw(cliques, with_labels=True)
In [218]:
f = nx.fiedler_vector(cliques)
print f
In [219]:
s = np.zeros(len(f))
s[f>0]=1
s = s.astype(int)
s = s.tolist()
print s, type(s)
In [220]:
colors = ['#d7191c', '#2b83ba']
node_colors = [ colors[s[v]] for v in cliques.nodes()]
nx.draw(cliques, node_color=node_colors, with_labels='True')
In [221]:
L = nx.laplacian_matrix(cliques).astype(float)
w,v = sp.sparse.linalg.eigsh(L, k = 3, which='SM')
In [222]:
print w
print v
In [223]:
print w.shape, v.shape
X = v*w
In [224]:
kmeans = KMeans(init='k-means++', n_clusters=3, n_init=10)
kmeans.fit_predict(X)
centroids = kmeans.cluster_centers_
labels = kmeans.labels_
error = kmeans.inertia_
In [225]:
print labels
In [226]:
colors = ['#d7191c', '#ffffbf', '#2b83ba']
node_colors = [ colors[labels[v]] for v in cliques.nodes()]
nx.draw(cliques, node_color=node_colors, with_labels='True')
In [181]:
# Code for setting the style of the notebook
from IPython.core.display import HTML
def css_styling():
styles = open("../theme/custom.css", "r").read()
return HTML(styles)
css_styling()