-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrectangle_model.py
executable file
·724 lines (531 loc) · 23.2 KB
/
rectangle_model.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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import entropy
def find_problem(index, all_problems):
"""Return flat and non flat representations of a specific problem"""
# Make 3d matrix
h = np.array([i for i in all_problems.loc[index, :]
.to_numpy(dtype=object)])
# Make array of arrays
h_flat = all_problems.loc[index, :].to_numpy(dtype=object)
return h, h_flat
def plot_problem(h):
"""Plot problem given 3d matrix representation of h"""
fig, ax = plt.subplots(1, 4, figsize=(16, 4))
opt_labels = ['$h_1$', '$h_2$', '$h_3$', '$h_4$']
for idx, ax_i in enumerate(ax):
hm = sns.heatmap(h[idx, :, :], ax=ax_i,
cmap='gray_r', cbar=False,
linewidths=2, linecolor='#808080')
ax_i.set(xticks=[], yticks=[], title=opt_labels[idx])
def get_pos_idx(concept):
pos_coords = np.nonzero(concept)
pos_idx = np.ravel_multi_index(pos_coords, (6, 6))
return list(pos_idx)
def find_pos_ex_indices(h_flat):
"""Extract indices (flattened) of positive examples for each h_i"""
d_possible = {}
for ex in range(len(h_flat)):
d_possible[ex] = get_pos_idx(h_flat[ex])
return d_possible
def make_df_iteration_zero(d_possible, h_flat):
"""Given pos example indices, return normalized iteration 0 df"""
df_0 = pd.DataFrame(index=[i for i in range(h_flat[0].size)],
columns=[i for i in range(h_flat.size)])
for k, v in d_possible.items():
for i in v:
df_0.loc[i, k] = 1
# Columns should sum up to 1
df_0 = df_0.div(df_0.sum(axis=1).replace(0, np.nan), axis=0)
df_0 = df_0.fillna(0)
df_0.columns = ['h_1', 'h_2', 'h_3', 'h_4']
return df_0
def plot_prob_heatmap(df, title):
"""Plot heatmap similar to that in the Shafto paper (not used here)"""
plt.figure(figsize=(4.8, 7))
sns.heatmap(df, annot=True, linewidths=0.25)
plt.title(title)
plt.show()
def find_teacher_probabilities_given_iter_0(n, df_0):
"""
Iterate over the model.
Args:
n (int): number of iterations
df_0 (DataFrame): P(h|d) for iteration 0
Returns:
df_d (DataFrame): P(d|h) after iteration n
df_h (DataFrame): P(h|d) after iteration n
"""
n_iter = n
df_h = df_0
for n in range(n_iter):
df_d = df_h.div(df_h.sum(axis=0), axis=1) # P(d|h)
df_h = df_d.div(df_d.sum(axis=1).replace(0, np.nan), axis=0) # P(h|d)
if n_iter == 0:
df_h = df_0
df_d = df_h.div(df_h.sum(axis=0), axis=1)
return df_d, df_h
def find_teacher_probs_k1(n_iter, prob_idx, all_problems):
"""
Return P(d|h) and P(h|d) after n interations for k=1
Args:
n_iter (int): number of iterations
prob_idx (str): index of problem
all_problems (DataFrame): df of all problems
Returns:
df_d (DataFrame): P(d|h) after n_iter
df_h (DataFrame): P(h|d) after n_iter
"""
_, h_flat = find_problem(prob_idx, all_problems)
d_possible = find_pos_ex_indices(h_flat)
df_0 = make_df_iteration_zero(d_possible, h_flat)
df_d, df_h = find_teacher_probabilities_given_iter_0(n_iter, df_0)
df_d = df_d.fillna(0)
df_h = df_h.fillna(0)
return df_d, df_h
def drop_zero_rows(df):
df = df.loc[(df != 0).any(axis=1)]
return df
def plot_problem_with_indices(h_flat, h):
"""Plot problem with indices to make viz slightly easier"""
indices = np.arange(0, h_flat[0].size).reshape(6, 6)
fig, ax = plt.subplots(1, 4, figsize=(16, 4))
opt_labels = '0123'
for idx, ax_i in enumerate(ax):
hm = sns.heatmap(h[idx, :, :], ax=ax_i,
cmap='gray_r', cbar=False,
linewidths=2, linecolor='#808080', annot=indices)
ax_i.set(xticks=[], yticks=[], title=opt_labels[idx])
def make_prob_heatmap_k1(df):
probs = np.array([df[i].fillna(0).to_numpy().reshape(6,6)
for i in df.columns])
return probs
def plot_prob_heatmap_k1(df, title):
'''Plot probabilities heatmap for k=1 given either df_d or df_h'''
problem = make_prob_heatmap_k1(df)
fig, ax = plt.subplots(1, 4, figsize=(16, 4))
fig.suptitle(title, y=1.1)
opt_labels = ['$h_1$', '$h_2$', '$h_3$', '$h_4$']
for idx, ax_i in enumerate(ax):
hm = sns.heatmap(problem[idx, :, :], ax=ax_i,
cmap='GnBu', cbar=False,
linewidths=2, linecolor='#808080', annot=True,
fmt='.1g', annot_kws={"size": 10})
ax_i.set(xticks=[], yticks=[], title=opt_labels[idx])
def make_empty_df_2ex():
indices = []
for i in range(36):
for j in range(i+1, 36):
indices.append((i, j))
indices = pd.MultiIndex.from_tuples(indices, names=('i_1', 'i_2'))
df_2ex = pd.DataFrame(columns=['h_1', 'h_2', 'h_3', 'h_4'], index=indices)
return df_2ex
def make_empty_df_3ex():
indices = []
for i in range(36):
for j in range(i+1, 36):
for k in range(j+1, 36):
indices.append((i, j, k))
indices = pd.MultiIndex.from_tuples(indices, names=('i_1', 'i_2', 'i_3'))
df_3ex = pd.DataFrame(columns=['h_1', 'h_2', 'h_3', 'h_4'], index=indices)
return df_3ex
def make_empty_df_4ex():
indices = []
for i in range(36):
for j in range(i+1, 36):
for k in range(j+1, 36):
for l in range(k+1, 36):
indices.append((i, j, k, l))
indices = pd.MultiIndex.from_tuples(indices, names=('i_1', 'i_2', 'i_3', 'i_4'))
df_3ex = pd.DataFrame(columns=['h_1', 'h_2', 'h_3', 'h_4'], index=indices)
return df_3ex
def make_empty_df_5ex():
indices = []
for i in range(36):
for j in range(i+1, 36):
for k in range(j+1, 36):
for l in range(k+1, 36):
for m in range(l+1, 36):
indices.append((i, j, k, l, m))
indices = pd.MultiIndex.from_tuples(indices, names=('i_1', 'i_2', 'i_3', 'i_4', 'i_5'))
df_3ex = pd.DataFrame(columns=['h_1', 'h_2', 'h_3', 'h_4'], index=indices)
return df_3ex
def make_empty_df_6ex():
indices = []
for i in range(36):
for j in range(i+1, 36):
for k in range(j+1, 36):
for l in range(k+1, 36):
for m in range(l+1, 36):
for n in range(m+1, 36):
indices.append((i, j, k, l, m, n))
indices = pd.MultiIndex.from_tuples(indices, names=('i_1', 'i_2', 'i_3', 'i_4', 'i_5', 'i_6'))
df_3ex = pd.DataFrame(columns=['h_1', 'h_2', 'h_3', 'h_4'], index=indices)
return df_3ex
def make_d_possible_with_column_labels(h_flat):
"""Find possible indices, but keys are labels h_i instead"""
columns = ['h_1', 'h_2', 'h_3', 'h_4']
d_possible = find_pos_ex_indices(h_flat)
new_d_possible = {}
for ex in range(len(columns)):
new_d_possible[columns[ex]] = d_possible[ex]
return new_d_possible
def normalize_probs_and_fill_nans(df):
"""Columns (each of the h_i) should sum up to 1"""
df = df.div(df.sum(axis=1).replace(0, np.nan), axis=0)
df = df.fillna(0)
return df
def fill_df_2ex(h_flat):
'''Fill df with initial probabilities for k=2'''
df_2ex = make_empty_df_2ex()
new_d_possible = make_d_possible_with_column_labels(h_flat)
for column in df_2ex.columns:
for i, j in df_2ex.index:
if i in new_d_possible[column] and j in new_d_possible[column]:
df_2ex.loc[(i,j), column] = 1
df_2ex_short = df_2ex.dropna(how='all')
df_2ex = normalize_probs_and_fill_nans(df_2ex)
df_2ex_short = normalize_probs_and_fill_nans(df_2ex_short)
return df_2ex, df_2ex_short
def find_teacher_probs_k2(n_iter, prob_idx, all_problems):
"""
Return P(d|h) and P(h|d) after n interations for k=2
Args:
n_iter (int): number of iterations
prob_idx (str): index of problem
all_problems (DataFrame): df of all problems
Returns:
df_d (DataFrame): P(d|h) after n_iter
df_h (DataFrame): P(h|d) after n_iter
"""
_, h_flat = find_problem(prob_idx, all_problems)
df_2ex_0, _ = fill_df_2ex(h_flat)
df_d, df_h = find_teacher_probabilities_given_iter_0(n_iter, df_2ex_0)
df_d = df_d.fillna(0)
df_h = df_h.fillna(0)
return df_d, df_h
def make_prob_heatmap_k2(df):
probs = np.array([np.zeros((6, 6)) for column in df.columns])
for h_idx in range(df.columns.size):
for i_1, i_2 in df.index:
probs[h_idx, np.unravel_index(i_1, (6, 6))[0],
np.unravel_index(i_1, (6, 6))[1]] += df.loc[(i_1, i_2),
df.columns[h_idx]]
probs[h_idx, np.unravel_index(i_2, (6, 6))[0],
np.unravel_index(i_2, (6, 6))[1]] += df.loc[(i_1, i_2),
df.columns[h_idx]]
# correct for double counting
# probs = probs / 2
return probs
def plot_problem_heatmap(df, title):
'''Plot probabilities heatmap given probabilities df'''
problem = df
# problem = np.array([df[i].fillna(0).to_numpy().reshape(6,6) for i in df.columns])
fig, ax = plt.subplots(1, 4, figsize = (16, 4))
fig.suptitle(title, y=1.1)
opt_labels = ['$h_1$', '$h_2$', '$h_3$', '$h_4$']
for idx, ax_i in enumerate(ax):
hm = sns.heatmap(problem[idx, :, :], ax=ax_i,
cmap='GnBu', cbar=False,
linewidths=2, linecolor='#808080', annot=True,
fmt='.1g', annot_kws={"size": 10})
ax_i.set(xticks=[], yticks=[], title=opt_labels[idx])
def fill_df_3ex(h_flat):
'''Fill df with initial probabilities for k=3'''
df_3ex = make_empty_df_3ex()
new_d_possible = make_d_possible_with_column_labels(h_flat)
for column in df_3ex.columns:
for i, j, k in df_3ex.index:
if i in new_d_possible[column] and j in new_d_possible[column] and k in new_d_possible[column]:
df_3ex.loc[(i, j, k), column] = 1
df_3ex_short = df_3ex.dropna(how='all')
df_3ex = normalize_probs_and_fill_nans(df_3ex)
df_3ex_short = normalize_probs_and_fill_nans(df_3ex_short)
return df_3ex, df_3ex_short
def fill_df_4ex(h_flat):
'''Fill df with initial probabilities for k=3'''
df_4ex = make_empty_df_4ex()
new_d_possible = make_d_possible_with_column_labels(h_flat)
for column in df_4ex.columns:
for i, j, k, l in df_4ex.index:
if i in new_d_possible[column] and j in new_d_possible[column] and k in new_d_possible[column] and l in new_d_possible[column]:
df_4ex.loc[(i, j, k, l), column] = 1
df_4ex_short = df_4ex.dropna(how='all')
df_4ex = normalize_probs_and_fill_nans(df_4ex)
df_4ex_short = normalize_probs_and_fill_nans(df_4ex_short)
return df_4ex, df_4ex_short
def fill_df_5ex(h_flat):
'''Fill df with initial probabilities for k=3'''
df_4ex = make_empty_df_5ex()
new_d_possible = make_d_possible_with_column_labels(h_flat)
for column in df_4ex.columns:
for i, j, k, l, m in df_4ex.index:
if i in new_d_possible[column] and j in new_d_possible[column] and k in new_d_possible[column] and l in new_d_possible[column] and m in new_d_possible[column]:
df_4ex.loc[(i, j, k, l, m), column] = 1
df_4ex_short = df_4ex.dropna(how='all')
df_4ex = normalize_probs_and_fill_nans(df_4ex)
df_4ex_short = normalize_probs_and_fill_nans(df_4ex_short)
return df_4ex, df_4ex_short
def fill_df_6ex(h_flat):
'''Fill df with initial probabilities for k=3'''
df_4ex = make_empty_df_6ex()
new_d_possible = make_d_possible_with_column_labels(h_flat)
for column in df_4ex.columns:
for i, j, k, l, m, n in df_4ex.index:
if i in new_d_possible[column] and j in new_d_possible[column] and k in new_d_possible[column] and l in new_d_possible[column] and m in new_d_possible[column] and n in new_d_possible[column]:
df_4ex.loc[(i, j, k, l, m, n), column] = 1
df_4ex_short = df_4ex.dropna(how='all')
df_4ex = normalize_probs_and_fill_nans(df_4ex)
df_4ex_short = normalize_probs_and_fill_nans(df_4ex_short)
return df_4ex, df_4ex_short
def find_teacher_probs_k3(n_iter, prob_idx, all_problems):
"""
Return P(d|h) and P(h|d) after n interations for k=3
Args:
n_iter (int): number of iterations
prob_idx (str): index of problem
all_problems (DataFrame): df of all problems
Returns:
df_d (DataFrame): P(d|h) after n_iter
df_h (DataFrame): P(h|d) after n_iter
"""
_, h_flat = find_problem(prob_idx, all_problems)
df_0, _ = fill_df_3ex(h_flat)
df_d, df_h = find_teacher_probabilities_given_iter_0(n_iter, df_0)
df_d = df_d.fillna(0)
df_h = df_h.fillna(0)
return df_d, df_h
def find_teacher_probs_k4(n_iter, prob_idx, all_problems):
"""
Return P(d|h) and P(h|d) after n interations for k=4
Args:
n_iter (int): number of iterations
prob_idx (str): index of problem
all_problems (DataFrame): df of all problems
Returns:
df_d (DataFrame): P(d|h) after n_iter
df_h (DataFrame): P(h|d) after n_iter
"""
_, h_flat = find_problem(prob_idx, all_problems)
df_0, _ = fill_df_4ex(h_flat)
df_d, df_h = find_teacher_probabilities_given_iter_0(n_iter, df_0)
df_d = df_d.fillna(0)
df_h = df_h.fillna(0)
return df_d, df_h
def find_teacher_probs_k5(n_iter, prob_idx, all_problems):
"""
Return P(d|h) and P(h|d) after n interations for k=4
Args:
n_iter (int): number of iterations
prob_idx (str): index of problem
all_problems (DataFrame): df of all problems
Returns:
df_d (DataFrame): P(d|h) after n_iter
df_h (DataFrame): P(h|d) after n_iter
"""
_, h_flat = find_problem(prob_idx, all_problems)
df_0, _ = fill_df_5ex(h_flat)
df_d, df_h = find_teacher_probabilities_given_iter_0(n_iter, df_0)
df_d = df_d.fillna(0)
df_h = df_h.fillna(0)
return df_d, df_h
def find_teacher_probs_k6(n_iter, prob_idx, all_problems):
"""
Return P(d|h) and P(h|d) after n interations for k=4
Args:
n_iter (int): number of iterations
prob_idx (str): index of problem
all_problems (DataFrame): df of all problems
Returns:
df_d (DataFrame): P(d|h) after n_iter
df_h (DataFrame): P(h|d) after n_iter
"""
_, h_flat = find_problem(prob_idx, all_problems)
df_0, _ = fill_df_6ex(h_flat)
df_d, df_h = find_teacher_probabilities_given_iter_0(n_iter, df_0)
df_d = df_d.fillna(0)
df_h = df_h.fillna(0)
return df_d, df_h
def make_prob_heatmap_k3(df):
probs = np.array([np.zeros((6, 6)) for column in df.columns])
for h_idx in range(df.columns.size):
for i_1, i_2, i_3 in df.index:
probs[h_idx, np.unravel_index(i_1, (6, 6))[0],
np.unravel_index(i_1, (6, 6))[1]] += df.loc[(i_1, i_2, i_3),
df.columns[h_idx]]
probs[h_idx, np.unravel_index(i_2, (6, 6))[0],
np.unravel_index(i_2, (6, 6))[1]] += df.loc[(i_1, i_2, i_3),
df.columns[h_idx]]
probs[h_idx, np.unravel_index(i_3, (6, 6))[0],
np.unravel_index(i_3, (6, 6))[1]] += df.loc[(i_1, i_2, i_3),
df.columns[h_idx]]
# probs = probs / 6
return probs
def make_prob_heatmap(df):
if len(df.index.names) == 1:
heatmap = make_prob_heatmap_k1(df)
elif len(df.index.names) == 2:
heatmap = make_prob_heatmap_k2(df)
else:
heatmap = make_prob_heatmap_k3(df)
return heatmap
def make_and_plot_prob_heatmap(df, title):
heatmap = make_prob_heatmap(df)
plot_problem_heatmap(heatmap, title)
return heatmap
def sort_values_ascending_by_column(df, label):
df = df.sort_values(by=[label], ascending=False)
return df
def plot_some_examples(df, title):
'''Plot four examples'''
problem = df
fig, ax = plt.subplots(1, 4, figsize = (16, 4))
fig.suptitle(title, y=1.1)
for idx,ax_i in enumerate(ax):
hm = sns.heatmap(problem[idx,:,:], ax=ax_i,
cmap='GnBu', cbar=False,
linewidths=2, linecolor='#808080', annot=True, fmt='.1g',
annot_kws={"size": 10})
ax_i.set(xticks=[], yticks=[])
# %% External functions
def find_teacher_probs(n_iter, prob_idx, all_problems):
"""
Creates a dict of probability dataframes for a specific problem
Args:
n_iter (int): n iterations
prob_idx (int): index of problem
all_problems (df): df of all problems
Returns:
my_dict (dict): dict indexed by k and ('h' or 'd')
"""
my_dict = {}
my_dict['n_iter'] = n_iter
my_dict['problem_index'] = prob_idx
for k in range(1, 7):
my_dict[k] = {}
my_dict[1]['d'], my_dict[1]['h'] = find_teacher_probs_k1(n_iter, prob_idx, all_problems)
my_dict[2]['d'], my_dict[2]['h'] = find_teacher_probs_k2(n_iter, prob_idx, all_problems)
my_dict[3]['d'], my_dict[3]['h'] = find_teacher_probs_k3(n_iter, prob_idx, all_problems)
my_dict[4]['d'], my_dict[4]['h'] = find_teacher_probs_k4(n_iter, prob_idx, all_problems)
my_dict[5]['d'], my_dict[5]['h'] = find_teacher_probs_k5(n_iter, prob_idx, all_problems)
my_dict[6]['d'], my_dict[6]['h'] = find_teacher_probs_k6(n_iter, prob_idx, all_problems)
return my_dict
def plot_high_prob_examples(prob, n_iter, types, idx, all_problems):
"""
Plot 4 high probablility examples for h_1, alongside the problem
Args:
prob (dict): dict of prob dfs for a specific problem (output of find_teacher_probs)
n_iter (int): # iterations
types (str): either 'd' (for P(d|h)) or 'h' (for P(h|d))
idx (int): index of problem (for title)
all_problems (df): df of all problems
Returns:
None.
"""
plot_problem(find_problem(idx, all_problems)[0])
for k in range(1, 4):
df = prob[n_iter][k][types]
df = sort_values_ascending_by_column(df, 'h_1')
ex = np.array([np.zeros((6, 6)) for column in df.columns])
try:
_ = df.index.levels
except AttributeError: # No index levels, meaning that k=1
for i, row in df.head(4).reset_index().iterrows():
ex[i, np.unravel_index(int(row[0]), (6, 6))[0], np.unravel_index(int(row[0]), (6, 6))[1]] = 1
else:
if len(df.index.levels) == 3:
for i, row in df.head(4).reset_index().iterrows():
ex[i, np.unravel_index(int(row['i_1']), (6,6))[0], np.unravel_index(int(row['i_1']), (6,6))[1]] = 1
ex[i, np.unravel_index(int(row['i_2']), (6,6))[0], np.unravel_index(int(row['i_2']), (6,6))[1]] = 1
ex[i, np.unravel_index(int(row['i_3']), (6,6))[0], np.unravel_index(int(row['i_3']), (6,6))[1]] = 1
elif len(df.index.levels) == 2:
for i, row in df.head(4).reset_index().iterrows():
ex[i, np.unravel_index(int(row['i_1']), (6,6))[0], np.unravel_index(int(row['i_1']), (6,6))[1]] = 1
ex[i, np.unravel_index(int(row['i_2']), (6,6))[0], np.unravel_index(int(row['i_2']), (6,6))[1]] = 1
plot_some_examples(ex, f'Examples for $h_1$, k={k}')
def plot_pragmatic_literal_successive_probs_with_entropy(problem, exs, problem_index):
# Probabilities over h_1
p_h1_0 = [problem[0][1]['h'].loc[exs[0], 'h_1'],
problem[0][2]['h'].loc[exs[1], 'h_1'],
problem[0][3]['h'].loc[exs[2], 'h_1']]
p_h1_500 = [problem[500][1]['h'].loc[exs[0], 'h_1'],
problem[500][2]['h'].loc[exs[1], 'h_1'],
problem[500][3]['h'].loc[exs[2], 'h_1']]
n_ex = range(1,4)
# Probabilities over all hypotheses
p_h_0 = [problem[0][1]['h'].loc[exs[0]],
problem[0][2]['h'].loc[exs[1]],
problem[0][3]['h'].loc[exs[2]]]
p_h_500 = [problem[500][1]['h'].loc[exs[0]],
problem[500][2]['h'].loc[exs[1]],
problem[500][3]['h'].loc[exs[2]]]
# Calculate entropy
s_0 = [entropy(p_h_0[i].to_numpy()) for i in range(len(p_h_0))]
s_500 = [entropy(p_h_500[i].to_numpy()) for i in range(len(p_h_500))]
plt.figure(figsize=(8, 6))
plt.plot(n_ex, p_h1_0, 'b--', label='Literal')
plt.plot(n_ex, p_h1_500, 'b', label='Pragmatic')
plt.title(f'Problem {problem_index}, learner\'s belief in $h_1$')
plt.xlabel('Examples')
plt.ylabel('$P(h_1|d)$')
plt.xticks(n_ex, exs)
plt.ylim((-0.05, 1.05))
plt.tick_params(axis='y', labelcolor='b')
plt.legend(loc='lower left', title='$P(h_1|d)$')
plt.twinx()
plt.plot(n_ex, s_0, 'g--', label='Literal')
plt.plot(n_ex, s_500, 'g', label='Pragmatic')
plt.ylabel('Entropy')
plt.tick_params(axis='y', labelcolor='g')
plt.legend(loc='upper left', title='Entropy')
#plt.tight_layout()
plt.show()
def plot_pragmatic_literal_successive_probs(problem, exs, problem_index):
plt.figure()
p_h_0 = [problem[0][1]['h'].loc[exs[0], 'h_1'],
problem[0][2]['h'].loc[exs[1], 'h_1'],
problem[0][3]['h'].loc[exs[2], 'h_1']]
p_h_500 = [problem[500][1]['h'].loc[exs[0], 'h_1'],
problem[500][2]['h'].loc[exs[1], 'h_1'],
problem[500][3]['h'].loc[exs[2], 'h_1']]
n_ex = range(1, 4)
plt.plot(n_ex, p_h_0, label='Literal')
plt.plot(n_ex, p_h_500, label='Pragmatic')
plt.title(f'Problem {problem_index}, learner\'s belief in $h_1$')
plt.xlabel('Examples')
plt.ylabel('$P(h_1|d)$')
plt.xticks(n_ex, exs)
plt.ylim((-0.05, 1.05))
plt.legend()
plt.show()
def make_many_plots(all_problems, problem_index):
# Plot a few high probability examples
problem = {}
problem[0] = find_teacher_probs(0, problem_index, all_problems) # 0 iterations
problem[500] = find_teacher_probs(500, problem_index, all_problems)
plot_high_prob_examples(problem, 500, 'd', problem_index, all_problems)
# Plot heatmap
iters = [0, 500]
k_values = [1, 2, 3]
types = {'d': '$P(d|h)$', 'h': '$P(h|d)$'}
for k in k_values:
for i in iters:
for t, v in types.items():
_ = make_and_plot_prob_heatmap(problem[i][k][t], f'{i} iterations, k={k}, {v}')
# Find a few high quality examples and plot
ex_seqs = []
exs = sort_values_ascending_by_column(problem[500][3]['h'], 'h_1').head(5).index # randomize later?
for ex in exs:
ex_seqs.append([(ex[0]), (ex[0], ex[1]), (ex[0], ex[1], ex[2])])
ex_seqs.append([(ex[0]), (ex[0], ex[2]), (ex[0], ex[1], ex[2])])
ex_seqs.append([(ex[1]), (ex[0], ex[1]), (ex[0], ex[1], ex[2])])
ex_seqs.append([(ex[1]), (ex[1], ex[2]), (ex[0], ex[1], ex[2])])
ex_seqs.append([(ex[2]), (ex[1], ex[2]), (ex[0], ex[1], ex[2])])
ex_seqs.append([(ex[2]), (ex[0], ex[2]), (ex[0], ex[1], ex[2])])
# Plot pragmatic vs. literal listener plots with entropy
for i in range(len(ex_seqs)):
plot_pragmatic_literal_successive_probs_with_entropy(problem, ex_seqs[i], problem_index)