-
Notifications
You must be signed in to change notification settings - Fork 0
/
clustering.py
129 lines (111 loc) · 3.9 KB
/
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import sklearn
from pandas import *
import numpy as np
from sklearn.cluster import KMeans
from sklearn.mixture import VBGMM, DPGMM
from sklearn import cluster
from sklearn import mixture
import networkx as nx
import csv
import numpy as np
import matplotlib.pyplot as plt
import scipy
MAKE_GRAPH=1
## Seperate Clustering Script
def load_data(path):
lookup_dict={}
with open(path, 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='"')
for row in spamreader:
lookup_dict[row[4]]={"url":row[6]}
return lookup_dict
def create_html(links,fname):
#creates HTML renditions for display in app
file=open(fname,"w+")
file.write("{% extends 'basetemp.html' %}\n \
{% block head %}\n \
{{ super() }}\n \
{% endblock %}\n \
{% block content %}\n")
for item in links:
file.write("<img src="+item+" height='100' width='100'>\n")
file.write("{% endblock %}\n")
def output_clusters(clusters,fname):
file=open(fname,"w+")
for item in clusters:
file.write(','.join(item)+'\n')
def main(method,cluster_num=30,alpha=.5):
f ='/Users/davidgreenfield/Downloads/features_csv_tmp.csv'
#f ='/Users/davidgreenfield/Downloads/features_f500.csv'
cols=range(1,4096)
feats =np.loadtxt(open(f,"rb"),delimiter=",",skiprows=1,usecols=(cols))
asins = np.loadtxt(open(f,"rb"),delimiter=",",skiprows=1,usecols=([0]),dtype=str)
if method == 'kmeans':
k_means=cluster.KMeans(n_clusters=cluster_num)
k_means.fit(feats)
y = k_means.labels_
if MAKE_GRAPH==1:
print "hello 1"
create_graph(k_means)
elif method == 'GMM_VB':
gmm_vb = VBGMM.fit(feats,n_components=50,alpha=.5)
y = gmm_vb.predict(feats)
cluster_no = len(np.unique(y))
elif method == 'GMM_DP':
gmm_dp = DPGMM(n_components=50,alpha=alpha)
gmm_dp.fit(feats)
y = gmm_dp.predict(feats)
cluster_no = len(np.unique(y))
clusters=[]
groups={}
data=load_data('./data/boots_aws.csv')
for i in range(0,cluster_num):
groups[i]=np.where(y==i)
ids=asins[groups[i]]
clusters.append(ids)
links=[data[x]['url'] for x in ids]
create_html(links,"templates/groups/group"+str(i)+".html")
output_clusters(clusters,"outputs/clusters.csv")
def create_graph(k_means):
"""
Testing graph structure of cluster centers based on N nearest neighbors
"""
centers=k_means.cluster_centers_
G=nx.Graph()
labels={}
dist_mat=np.zeros((len(centers),len(centers)))
dist_mat_cos=np.zeros((len(centers),len(centers)))
all_dist=[]
for i,clust in enumerate(centers):
for y in range(0,len(centers)):
dist=scipy.spatial.distance.euclidean(centers[i],centers[y])
dist_cos=scipy.spatial.distance.cosine(centers[i],centers[y])
if i==y:
dist=10000000
dist_mat[i][y]=dist
dist_mat_cos[i][y]=dist_cos
all_dist.append(dist_cos)
for i,row in enumerate(dist_mat):
for neighbor in row.argsort()[:0]:
G.add_edge(i,neighbor)
for i,row in enumerate(dist_mat_cos):
for neighbor in row.argsort()[:4]:
if row[neighbor]>0:
G.add_edge(i,neighbor,weight=1/row[neighbor])
#for i,row in enumerate(dist_mat_cos):
# for y,pt in enumerate(row):
# if pt>np.percentile(all_dist,90):
# G.add_edge(i,y)
print G.nodes()
pos = nx.spring_layout(G,scale=4)
for lab in G.nodes():
labels[lab]=lab
nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'),label=True)
nx.draw_networkx_edges(G, pos, edgelist=G.edges(), edge_color='r', arrows=False)
nx.draw_networkx_labels(G,pos,labels,font_size=16)
plt.savefig('graph.png')
#plt.show()
return
#create a graph in networkX
if __name__ == '__main__':
main('kmeans')