import networkx as nx import matplotlib.pyplot as plt plt.xkcd() import numpy as np %matplotlib inline G = nx.read_gml(path = 'karate.gml') nx.draw_networkx(G) k = nx.degree(G) plt.figure(1, figsize=(10,7)) coord = nx.spring_layout(G) nx.draw_networkx(G, pos=coord, nodelist=k.keys(), node_size = [d*100 for d in k.values()], node_color=k.values(), font_size=8, cmap=plt.cm.Reds, ) # load adjacency matrix A = nx.to_numpy_matrix(G, dtype=np.bool) k = G.degree() # alternatevly you can find k as k = np.sum(A, axis=0) # sort nodes according to degree id_sort = np.array(sorted(k, key = k.get, reverse=True)) k_sort = np.array(k.values()) k_sort = k_sort[id_sort-1] # show adjacency matrix plt.figure(1, figsize=(6, 6)) plt.imshow(A, cmap="Greys", interpolation="none" ) plt.title('Zachary\'s club adjacency matrix', fontsize=14) # show node degrees plt.figure(1, figsize=(10, 5)) plt.bar(np.arange(34), k_sort) plt.xticks(np.arange(34), id_sort) plt.margins(0.2) plt.ylabel('Degree') plt.xlabel('Node id') # Write your code here # # # # load data D = np.loadtxt('bikinis.txt') y = D[:,0] X = D[:,1:] # Find regression coefs Beta = np.dot(np.dot(np.linalg.inv(np.dot(X.T, X)), X.T), y) # Make predictions yt = X.dot(Beta) # Calculate residuals res = y - yt # Plot plt.figure(figsize=(10,10)) plt.plot(yt, res, '+b') # Choose 2 dims and plot predictions agains the line X1 = X[:,0] idx = np.argsort(X1) yt1 = X1[idx].dot(Beta[0]) fig, ax = plt.subplots() fig.set_size_inches(7,7) ax.plot(X1, y, '.r', label='Data') ax.plot(X1[idx], yt1, 'b', label='Line') plt.xlabel('$x_1$') plt.ylabel('$y$') ax.legend(loc='upper left', shadow=True) # Write your code here # # # # Loading network G = nx.read_gml('network.gml') # Draw it! pos = nx.spring_layout(G, dim = 2, iterations=100) plt.figure(figsize =(7,7)) nx.draw(G, pos) print 'Network order {0:d}, Network size {1:d}'.format(G.order(), G.size()) # Degree distr k = G.degree() k = np.array(k.values()) n, bins, patches = plt.hist(k, bins = 10, facecolor='g') # Find nodes with highest degree idx = np.argsort(k) idx = idx[::-1] k_sorted = k[idx] v1 = G.node[idx[0]] print v1['label'] # Find connected components CC = nx.connected_components(G) for v in CC[0]: print G.node[v] SG = G.subgraph(CC[0]) nx.radius(SG)