-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKmeans_Standalone_DensityContours.py
164 lines (133 loc) · 5.19 KB
/
Kmeans_Standalone_DensityContours.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#!/usr/bin/python
""" Kmeans algorithm and output diagnostics in JSON """
""" From http://flothesof.github.io/k-means-numpy.html """
""" Load modules """
import numpy as np
import pandas as pd
import seaborn as sns; sns.set(color_codes=True)
import pylab as pl
from scipy import stats
import csv
""" Choose the dataset and the output directory """
folder = './'
target = '/Users/jmartinez/Sites/kmeansvisu_cargo/distill/Data/ContourPro/'
#dataset = 'UnequalVar'
#dataset = 'Mixture2D'
dataset = 'AnisotropBlob'
""" Read the data and calculate length """
filename = './data/'+dataset+'.csv'
data_points = pd.read_csv(filename, sep='\t', header=None)
datacount = len(data_points)
dataplot = data_points.values
""" Modules for the Kmeans calculation """
def initialize_centroids(points, clusters):
"""returns k centroids from the initial points"""
centroids = points.copy()
np.random.shuffle(centroids)
return centroids[:clusters]
def closest_centroid(points, centroids):
"""returns an array containing the index to the nearest centroid for each point"""
# distances = np.sqrt(((points - centroids[:, np.newaxis])**2).sum(axis=2))
distances = np.abs(points - centroids[:, np.newaxis]).sum(axis=2)
return np.argmin(distances, axis=0)
def calculate_inertia(points, closest, centroids):
# distances = np.sqrt(((points - centroids[:, np.newaxis])**2).sum(axis=2))
distances = np.abs(points - centroids[:, np.newaxis]).sum(axis=2)
return distances
def move_centroids(points, closest, centroids):
"""returns the new centroids assigned from the points closest to them"""
return np.array([points[closest==k].mean(axis=0) for k in range(centroids.shape[0])])
""" Parameter definition """
samples=1000
iterations=8
clusters=3
""" Storage of the variables """
cargo_centroid=[]
supercargo_centroid=[]
cargo_inertia=[]
supercargo_inertia=[]
cargo_clustersize=[]
cargo_shifts=[]
supercargo_shifts=[]
phase_x=[]
phase_y=[]
sphase_x=[]
sphase_y=[]
seacluster_x=[]
seacluster_y=[]
""" Loop for many initializations, or samples, over Kmeans """
for s in range(0,samples):
""" Initialize the random centroids """
c = initialize_centroids(dataplot,clusters)
for i in range(0,iterations):
""" Move the centroids """
mov = move_centroids(dataplot, closest_centroid(dataplot,c), c)
c = mov
cargo_centroid.append(c)
supercargo_centroid.append(c[:3])
cargo_centroid=[]
seacluster_x.append(c[0][0])
seacluster_y.append(c[0][1])
""" Calculate the sum of distances within each cluster """
inertia=calculate_inertia(dataplot, closest_centroid(dataplot,c), c)
for n in range(0,len(inertia)):
cargo_inertia.append(np.sum(inertia[n]))
supercargo_inertia.append(cargo_inertia)
cargo_inertia=[]
""" Count the number of datapoints in each cluster """
groups=closest_centroid(dataplot,c)
for m in range(0,clusters):
cargo_shifts.append(np.sum(np.count_nonzero(groups==m)))
supercargo_shifts.append(cargo_shifts)
cargo_shifts=[]
# Pairing the values for the phase space """
# for v in range(0,clusters):
# for j in range(0,iterations):
# phase_x.append(supercargo_shifts[j][v])
# phase_y.append(supercargo_inertia[j][v])
# sphase_x.append(phase_x)
# sphase_y.append(phase_y)
# phase_x=[]
# phase_y=[]
""" Pairing the values for the phase space """
for v in range(0,clusters):
# print(v)
for j in range(0,iterations):
# print(supercargo_centroid[j][v][0])
phase_x.append(supercargo_centroid[j][v][0])
phase_y.append(supercargo_centroid[j][v][1])
sphase_x.append(phase_x)
sphase_y.append(phase_y)
phase_x=[]
phase_y=[]
""" Save output in JSON format via Pandas """
phase_pd=pd.DataFrame({"phase_x":sphase_x[v],"phase_y":sphase_y[v]})
# phase_pd.reset_index().to_json(orient='records',path_or_buf=target+dataset+'_Contour_'+str(s)+'_'+str(v)+'.json')
sphase_x=[]
sphase_y=[]
supercargo_shifts=[]
supercargo_inertia=[]
supercargo_centroid=[]
""" Calculation of the density of points """
dim = 60
xedges = np.linspace(np.min(seacluster_x),np.max(seacluster_x),dim)
yedges = np.linspace(np.min(seacluster_y),np.max(seacluster_y),dim)
H, xedges, yedges = np.histogram2d(seacluster_x, seacluster_y, bins=(xedges, yedges))
Hprima = H * 0
Hnew = H * 0
for i in range(0,dim-1):
for j in range (0,dim-1):
Hprima[i][j]=(H[j][i])
for k in range(0,dim-1):
Hnew[k]=Hprima[(dim-2)-k]
""" Swap columns and rows for the D3.js required CSV / JSON format """
newH = Hnew.ravel()
strH=list(newH)
#np.savetxt(target+dataset+'New_Volcano_2.csv',newH,fmt='%d',delimiter=",")
my_df = pd.DataFrame(strH).T
my_df.to_csv(target+dataset+'_Volcano.csv', index=False, header=False)
#my_df.reset_index().to_json(orient='records',path_or_buf=target+'New_Volcano_2.json')
#with open(target+'New_Volcano_2.csv', "wb") as f:
# writer = csv.writer(f)
# writer.writerows(strH)
#np.savetxt(target+'New_Volcano_2.csv',strH,fmt='%d',delimiter=",")