forked from djstrouse/information-bottleneck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata_generation.py
648 lines (522 loc) · 17.7 KB
/
data_generation.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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
from IB import *
import matplotlib.pyplot as plt
import os
import numpy as np
def gen_easytest(plot=True):
# set name
name = "easytest"
n = 10
# set generative parameters
mu1 = np.array([0,0])
sig1 = np.eye(2)
n1 = n
mu2 = np.array([math.sqrt(75),5])
sig2 = np.eye(2)
n2 = n
mu3 = np.array([0,10])
sig3 = np.eye(2)
n3 = n
param = {'mu1': mu1, 'sig1': sig1, 'n1': n1,
'mu2': mu2, 'sig2': sig2, 'n2': n2,
'mu3': mu3, 'sig3': sig3, 'n3': n3}
# make labels
labels = np.array([0]*n1+[1]*n2+[2]*n3)
# make coordinates
coord = np.concatenate((np.random.multivariate_normal(mu1,sig1,n1),
np.random.multivariate_normal(mu2,sig2,n2),
np.random.multivariate_normal(mu3,sig3,n3)))
# make dataset
ds = dataset(coord = coord, labels = labels, gen_param = param, name = name)
# plot coordinates
if plot: ds.plot_coord()
# normalize
ds.normalize_coord()
if plot: ds.plot_coord()
return ds
def gen_blob(plot=True):
# set name
name = "blob"
# set generative parameters
mu1 = np.array([0,0])
sig1 = np.eye(2)
n1 = 90
param = {'mu1': mu1, 'sig1': sig1, 'n1': n1}
# make labels
labels = np.array([0]*n1)
# make coordinates
coord = np.random.multivariate_normal(mu1,sig1,n1)
# make dataset
ds = dataset(coord = coord, labels = labels, gen_param = param, name = name)
# plot coordinates
if plot: ds.plot_coord()
# normalize
ds.normalize_coord()
if plot: ds.plot_coord()
return ds
def gen_3sph_evensamp_evenspacing(plot=True):
# set name
name = "3sph_evensamp_evenspacing"
# set generative parameters
mu1 = np.array([0,0])
sig1 = np.eye(2)
n1 = 30
mu2 = np.array([math.sqrt(75),5])
sig2 = np.eye(2)
n2 = 30
mu3 = np.array([0,10])
sig3 = np.eye(2)
n3 = 30
param = {'mu1': mu1, 'sig1': sig1, 'n1': n1,
'mu2': mu2, 'sig2': sig2, 'n2': n2,
'mu3': mu3, 'sig3': sig3, 'n3': n3}
# make labels
labels = np.array([0]*n1+[1]*n2+[2]*n3)
# make coordinates
coord = np.concatenate((np.random.multivariate_normal(mu1,sig1,n1),
np.random.multivariate_normal(mu2,sig2,n2),
np.random.multivariate_normal(mu3,sig3,n3)))
# make dataset
ds = dataset(coord = coord, labels = labels, gen_param = param, name = name)
# plot coordinates
if plot: ds.plot_coord()
# normalize
ds.normalize_coord()
if plot: ds.plot_coord()
return ds
def gen_3sph_unevensamp_evenspacing(plot=True):
# set name
name = "3sph_unevensamp_evenspacing"
# set generative parameters
mu1 = np.array([0,0])
sig1 = np.eye(2)
n1 = 10
mu2 = np.array([math.sqrt(75),5])
sig2 = np.eye(2)
n2 = 30
mu3 = np.array([0,10])
sig3 = np.eye(2)
n3 = 60
param = {'mu1': mu1, 'sig1': sig1, 'n1': n1,
'mu2': mu2, 'sig2': sig2, 'n2': n2,
'mu3': mu3, 'sig3': sig3, 'n3': n3}
# make labels
labels = np.array([0]*n1+[1]*n2+[2]*n3)
# make coordinates
coord = np.concatenate((np.random.multivariate_normal(mu1,sig1,n1),
np.random.multivariate_normal(mu2,sig2,n2),
np.random.multivariate_normal(mu3,sig3,n3)))
# make dataset
ds = dataset(coord = coord, labels = labels, gen_param = param, name = name)
# plot coordinates
if plot: ds.plot_coord()
# normalize
ds.normalize_coord()
if plot: ds.plot_coord()
return ds
def gen_3sph_evensamp_unevenspacing(plot=True):
# set name
name = "3sph_evensamp_unevenspacing"
# set generative parameters
mu1 = np.array([0,2.5])
sig1 = np.eye(2)
n1 = 30
mu2 = np.array([0,-2.5])
sig2 = np.eye(2)
n2 = 30
mu3 = np.array([15,0])
sig3 = np.eye(2)
n3 = 30
param = {'mu1': mu1, 'sig1': sig1, 'n1': n1,
'mu2': mu2, 'sig2': sig2, 'n2': n2,
'mu3': mu3, 'sig3': sig3, 'n3': n3}
# make labels
labels = np.array([0]*n1+[1]*n2+[2]*n3)
# make coordinates
coord = np.concatenate((np.random.multivariate_normal(mu1,sig1,n1),
np.random.multivariate_normal(mu2,sig2,n2),
np.random.multivariate_normal(mu3,sig3,n3)))
# make dataset
ds = dataset(coord = coord, labels = labels, gen_param = param, name = name)
# plot coordinates
if plot: ds.plot_coord()
# normalize
ds.normalize_coord()
if plot: ds.plot_coord()
return ds
def make_circle(radius,num_points):
count = 0
points = np.zeros((num_points,2))
while count<num_points:
x1 = 2*radius*np.random.rand()-radius
x2 = 2*radius*np.random.rand()-radius
x = np.array([x1,x2])
if np.linalg.norm(x)<radius:
points[count,:] = x
count += 1
return points
def gen_mouse(plot=True):
# set name
name = "mouse"
# set generative parameters
mu1 = np.array([0,0])
rad1 = 4
n1 = 180
mu2 = np.array([-3.5,5])
rad2 = 1.4
n2 = 25
mu3 = np.array([3.5,5])
rad3 = 1.4
n3 = 25
param = {'mu1': mu1, 'rad1': rad1, 'n1': n1,
'mu2': mu2, 'rad2': rad2, 'n2': n2,
'mu3': mu3, 'rad3': rad3, 'n3': n3}
# make labels
labels = np.array([0]*n1+[1]*n2+[2]*n3)
# make coordinates
coord = np.concatenate((make_circle(rad1,n1)+mu1,
make_circle(rad2,n2)+mu2,
make_circle(rad3,n3)+mu3))
# make dataset
ds = dataset(coord = coord, labels = labels, gen_param = param, name = name)
# plot coordinates
if plot: ds.plot_coord()
# normalize
ds.normalize_coord()
if plot: ds.plot_coord()
return ds
def gen_circleandcigar(plot=True):
# set name
name = "circleandcigar"
# set generative parameters
mu1 = np.array([5,0])
sig1 = np.eye(2)
n1 = 50
mu2 = np.array([-5,0])
sig2 = np.array([[1,0],[0,25]])
n2 = 50
param = {'mu1': mu1, 'sig1': sig1, 'n1': n1,
'mu2': mu2, 'sig2': sig2, 'n2': n2}
# make labels
labels = np.array([0]*n1+[1]*n2)
# make coordinates
coord = np.concatenate((np.random.multivariate_normal(mu1,sig1,n1),
np.random.multivariate_normal(mu2,sig2,n2)))
# make dataset
ds = dataset(coord = coord, labels = labels, gen_param = param, name = name)
# plot coordinates
if plot: ds.plot_coord()
# normalize
ds.normalize_coord()
if plot: ds.plot_coord()
return ds
def gen_2cigars(plot=True):
# set name
name = "2cigars"
# set generative parameters
mu1 = np.array([0,-4])
sig1 = np.array([[25,0],[0,1]])
n1 = 50
mu2 = np.array([0,4])
sig2 = np.array([[25,0],[0,1]])
n2 = 50
param = {'mu1': mu1, 'sig1': sig1, 'n1': n1,
'mu2': mu2, 'sig2': sig2, 'n2': n2}
# make labels
labels = np.array([0]*n1+[1]*n2)
# make coordinates
coord = np.concatenate((np.random.multivariate_normal(mu1,sig1,n1),
np.random.multivariate_normal(mu2,sig2,n2)))
# make dataset
ds = dataset(coord = coord, labels = labels, gen_param = param, name = name)
# plot coordinates
if plot: ds.plot_coord()
# normalize
ds.normalize_coord()
if plot: ds.plot_coord()
return ds
def gen_2over3(plot=True):
# set name
name = "2over3"
# set generative parameters
sig = .75
mu1 = np.array([0,0])
sig1 = (sig**2)*np.eye(2)
n1 = 20
mu2 = np.array([-4,0])
sig2 = (sig**2)*np.eye(2)
n2 = 20
mu3 = np.array([4,0])
sig3 = (sig**2)*np.eye(2)
n3 = 20
mu4 = np.array([-2,12])
sig4 = (sig**2)*np.eye(2)
n4 = 20
mu5 = np.array([2,12])
sig5 = (sig**2)*np.eye(2)
n5 = 20
param = {'mu1': mu1, 'sig1': sig1, 'n1': n1,
'mu2': mu2, 'sig2': sig2, 'n2': n2,
'mu3': mu3, 'sig3': sig3, 'n3': n3,
'mu4': mu4, 'sig4': sig4, 'n4': n4,
'mu5': mu5, 'sig5': sig5, 'n5': n5}
# make labels
labels = np.array([0]*n1+[1]*n2+[2]*n3+[3]*n4+[4]*n5)
# make coordinates
coord = np.concatenate((np.random.multivariate_normal(mu1,sig1,n1),
np.random.multivariate_normal(mu2,sig2,n2),
np.random.multivariate_normal(mu3,sig3,n3),
np.random.multivariate_normal(mu4,sig4,n4),
np.random.multivariate_normal(mu5,sig5,n5)))
# make dataset
ds = dataset(coord = coord, labels = labels, gen_param = param, name = name)
# plot coordinates
if plot: ds.plot_coord()
# normalize
ds.normalize_coord()
if plot: ds.plot_coord()
return ds
def gen_halfconcentric(plot=True):
# set name
name = "halfconcentric"
# set generative parameters
nt = 80 # number of thetas
nd = 1 # number of samples per theta
no = nd*nt # number of samples for outer circle
ni = 20 # number of samples for inner circle
r = 5 # radius of outer loop
so = .25 # gaussian noise variance of outer circle
si = .25 # gaussian noise variance of inner circle
thetas = -np.linspace(0,math.pi,nt)
x = [r*math.cos(theta) for theta in thetas]
y = [r*math.sin(theta) for theta in thetas]
param = {'nt': nt, 'nd': nd, 'no': no, 'ni': ni, 'r': r, 'so': so, 'si': si}
# make labels
labels = np.array([0]*ni+[1]*no)
# make coordinates
coord = np.random.multivariate_normal(np.array([0,0]),si*np.eye(2),ni)
for i in range(len(x)):
coord = np.concatenate((coord,np.random.multivariate_normal(np.array([x[i],y[i]]),so*np.eye(2),nd)))
# make dataset
ds = dataset(coord = coord, labels = labels, gen_param = param, name = name)
# plot coordinates
if plot: ds.plot_coord()
# normalize
ds.normalize_coord()
if plot: ds.plot_coord()
return ds
def gen_concentric(plot=True):
# set name
name = "concentric"
# set generative parameters
nt = 80 # number of thetas
nd = 1 # number of samples per theta
no = nd*nt # number of samples for outer circle
ni = 20 # number of samples for inner circle
r = 8 # radius of outer loop
so = .25 # gaussian noise variance of outer circle
si = .25 # gaussian noise variance of inner circle
thetas = -np.linspace(0,2*math.pi,nt)
x = [r*math.cos(theta) for theta in thetas]
y = [r*math.sin(theta) for theta in thetas]
param = {'nt': nt, 'nd': nd, 'no': no, 'ni': ni, 'r': r, 'so': so, 'si': si}
# make labels
labels = np.array([0]*ni+[1]*no)
# make coordinates
coord = np.random.multivariate_normal(np.array([0,0]),si*np.eye(2),ni)
for i in range(len(x)):
coord = np.concatenate((coord,np.random.multivariate_normal(np.array([x[i],y[i]]),so*np.eye(2),nd)))
# make dataset
ds = dataset(coord = coord, labels = labels, gen_param = param, name = name)
# plot coordinates
if plot: ds.plot_coord()
# normalize
ds.normalize_coord()
if plot: ds.plot_coord()
return ds
# CODE BELOW NOT YET ADAPTED TO USE NEW IB DATASET CLASS
# GENERATE ONLY P(X,Y)
def gen_zipf_pxy():
X = 1024
Y = X
pxy = np.eye(X)
pxy = pxy/np.sum(pxy[:])
return pxy
def gen_blurred_diag_pxy(s):
X = 1024
Y = X
# generate pdf
from scipy.stats import multivariate_normal
pxy = np.zeros((X,Y))
rv = multivariate_normal(cov=s)
for x in range(X):
pxy[x,:] = np.roll(rv.pdf(np.linspace(-X/2,X/2,X+1)[:-1]),int(X/2+x))
pxy = pxy/np.sum(pxy)
# plot p(x,y)
import matplotlib.pyplot as plt
plt.figure()
plt.contourf(pxy)
plt.ion()
plt.title("p(x,y)")
plt.show()
return pxy
def gen_dir_pxy():
# param
X = 128
Y = 16
cx = 1000.
cys = np.logspace(-2.,1.,num=X,base=10)
# build pxy
px = np.random.dirichlet(cx*np.ones(X))
py_x = np.zeros((Y,X))
for x in range(X):
py_x[:,x] = np.random.dirichlet(cys[x]*np.ones(Y))
pxy = np.multiply(np.tile(px,(Y,1)),py_x).T
# plot p(x,y)
import matplotlib.pyplot as plt
plt.figure()
plt.contourf(pxy)
plt.ion()
plt.title("p(x,y)")
plt.show()
# plot histogram of H(p(y|x)) over x
plt.hist(entropy(py_x), bins='auto')
plt.title("entropies of conditionals p(y|x)")
plt.show()
# calc ixy
py = pxy.sum(axis=0)
hy = entropy(py)
hy_x = np.dot(px,entropy(py_x))
ixy = hy-hy_x
print("I(X;Y) = %.3f" % ixy)
return pxy
def gen_gaussian_pxy():
# param
cov = np.array([[1.5,1.1],[1.1,1]])
X = 128
Y = 128
xlow = -2
xhigh = 2
ylow = -2
yhigh = 2
#x, y = np.mgrid[-1.5:1.5:.01, -1.5:1.5:.01]
x,y = np.meshgrid(np.linspace(xlow,xhigh,X),np.linspace(ylow,yhigh,Y))
pos = np.empty(x.shape + (2,))
pos[:,:,0] = x; pos[:,:,1] = y
# generate pdf
from scipy.stats import multivariate_normal
import matplotlib.pyplot as plt
rv = multivariate_normal(cov=cov)
pxy = rv.pdf(pos)
pxy = pxy/np.sum(pxy)
# plot to make sure everything looks right
plt.figure()
plt.contourf(x, y, rv.pdf(pos))
plt.ion()
plt.show()
# calc ixy analytically and numerically
cx = abs(cov[0,0])
cy = abs(cov[1,1])
c = np.linalg.det(cov)
ixy_true = .5*math.log2((cx*cy)/c)
print("I(X;Y) = %.3f (analytical)" % ixy_true)
px = pxy.sum(axis=1)
py = pxy.sum(axis=0)
py_x = np.multiply(pxy.T,np.tile(1./px,(Y,1)))
hy = entropy(py)
hy_x = np.dot(px,entropy(py_x))
ixy_emp = hy-hy_x
print("I(X;Y) = %.3f (empirical)" % ixy_emp)
return pxy
def array_split2(x,f,minsize=1):
"""Splits numpy array x into two pieces, with f specifying fraction in 1st."""
X = len(x)
if X==1 or X<(2*minsize): # if too few elements, can't split
return [x]
i = math.floor(X*f)
if i<minsize:
i = minsize
x_split = [x[0:i],x[i:X]]
return x_split
def gen_hierarchical_pxy(component_type):
"""component_type in {uni,dir}"""
# todo:
# could have random num branches per split
# could bound independent contribution
import matplotlib.pyplot as plt
# param
X = 512
Y = 512
f = .5 # fraction to scale frozen p added at each depth
d = 6 # depth of tree
# total branches = b^d, X per branch = X/(b^d), assume b=2
if component_type=="dir":
cw = 1. # concentration for dirichlet over topic/level weights
cs = np.logspace(0.,-3.,num=d,base=10) # dirichlet concentrations for p(y|x) for each depth
elif component_type=="uni":
hmin = .7
hmax = 1.3
else:
raise ValueError("component_type must be uni or dir")
groups = [[list(range(X))]]
pxy = np.zeros((X,Y))
# make groups
for i in range(d):
newgroups = []
# loop over groups at this depth
for g in range(len(groups[i])):
group = groups[i][g]
# split group
minf = .3
maxf = .7
s = minf+np.random.rand(1)*(maxf-minf)
splitgroup = array_split2(group,s)
# and to new grouping
newgroups += splitgroup
groups += [newgroups]
if component_type=="dir":
# sample level mixture weights for each leaf
leafs = groups[d]
G = len(leafs) # number of leaf groups
W = np.zeros((G,d)) # mixture weights [=] leaves X tree depth
leaf_groups = np.zeros(X) # id of leaf group for each X
for g in range(G):
W[g,:] = np.random.dirichlet(cw*np.ones(d))
leaf_groups[leafs[g]] = g
leaf_groups = leaf_groups.astype(int)
# sample p(y|x) contributions for each depth
for i in range(d):
# ADDING TO P(Y|X) FOR EACH NEW GROUP
for g in range(len(groups[i+1])):
this_level = groups[i+1]
group = this_level[g]
# sample a contribution to p(y|x) for this group and add it to p(x,y)
x1 = group[0]
x2 = group[-1]
if component_type=="dir":
p = np.random.dirichlet(cs[i]*np.ones(Y)) # "node/topic" distributions
w_this_depth = W[:,i]
w_this_group = w_this_depth[leaf_groups[x1:(x2+1)]]
w = np.tile(w_this_group,(Y,1)).T
pxy[x1:(x2+1),:] += np.multiply(w,np.tile((f**i)*p,(x2+1-x1,1))) # assumes indices in group are consecutive and ordered!
elif component_type=="uni":
y1 = int(round((Y/X)*x1))
y2 = int(round((Y/X)*x2))
h = hmin+np.random.rand(1)*(hmin-hmax)
p = h*np.ones(y2+1-y1)/(y2+1-y1)
pxy[x1:(x2+1),y1:(y2+1)] += np.tile((f**i)*p,(x2+1-x1,1)) # assumes indices in group are consecutive and ordered!
# normalize
pxy = pxy/np.sum(pxy)
pxy2, px, py_x, hx, hy, hy_x, ixy, X, Y, zx, zy = process_pxy(pxy,0)
# plot p(x,y)
plt.figure()
plt.contourf(pxy)
plt.ion()
plt.show()
# plot histogram of H(p(y|x)) over x
print(entropy(py_x))
plt.hist(entropy(py_x), bins=10)
plt.title("entropies of conditionals p(y|x)")
plt.show()
# calc ixy
print("I(X;Y) = %.3f" % ixy)
return pxy, groups