-
Notifications
You must be signed in to change notification settings - Fork 0
/
william_davies_17012606.py
1960 lines (1802 loc) · 71.4 KB
/
william_davies_17012606.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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# %%
"""
# COMP0124 MAAI Individual Coursework
This 50-point individual coursework has four parts,
the Matrix Game, the Stochastic Game, the Nonzero-sum Game and Deep Multi-Agent Reinforcement Learning.
## Instructions
1. To start this CW, please duplicate this notebook at first:
- Choose "File => Save a copy in Drive" and open/run it in Colab.
- Or you can download the notebook and run it in your local jupyter notebook server.
2. For the coding assignment, please write your code at `### TODO ###` blocks or in a new cell. For analysis report, you are free to use as many blocks as you need.
3. Before submitting your notebook, **make sure that it runs without errors**, we also provide a validation tool in the end of this notebook.
- To check this, reload your notebook and the Python kernel, and run the notebook from the first to the last cell.
- Please do not change any methods or variables' name in the notebook, otherwise, you cannot get marking correctly.
- We would not help you debug the code, if we cannot run your submitted notebook, you will get zero point.
4. Download your notebook and submit it on Moodle.
- Click on "File -> Download .ipynb".
- Rename your notebook to ***firstname_lastname_studentnumber.ipynb***. (Please strictly follow the naming requirement.)
- Upload to Moodle.
5. This CW would due by **23:55 26/03/2021**, please submit your .ipynb file through the [submission entrance](https://moodle.ucl.ac.uk/mod/assign/view.php?id=1685901).
6. If you have any questions, please contact TAs: [Minne Li]([email protected]), [Oliver Slumbers]([email protected]), [Xihan Li]([email protected]), [Xidong Feng]([email protected]), and [Mengyue Yang]([email protected]).
"""
# # %%
# import math
# from scipy import special
#
# # %%
# """
# ## Part I: Matrix Game (10 points)
#
# We start with the simplest setting: Matrix Game (a.k.a Stage Game/Normal Form Game). In this part, you will try to solve the matrix game with full knowledge of the payoff for each player in the game.
#
#
#
# Given a two-player, two-action matrix game, we have the payoff matrices as follows:
# $$
# \mathbf{R}^1 = \left[\begin{matrix}
# 0 & 3 \\
# 1 &2
# \end{matrix}\right]
# \quad
# \mathbf{R}^2 = \left[\begin{matrix}
# 3 & 2 \\
# 0 & 1
# \end{matrix}\right]
# $$
#
# Each player selects an action from the action space $\{1,2\}$ which determines the payoffs to the players. If the player 1 chooses action $i$ and the player 2 chooses action $j$, then the player 1 and player2 receive the rewards $r^1_{ij}$ and $r^2_{ij}$ respectively. For example, if both players choose action $1$, then the player 1 would have $r^1_{11}=0$ and player 1 would receive $r^2_{11}=3$.
#
# Then, we can use $\alpha\in [0,1] $ represents the strategy for player 1, where $\alpha$ corresponds to the probability of player 1 selecting the first action (action 1), and $1-\alpha$ is the probability of choosing the second action (action 2). Similarly, we use $\beta$ to be the strategy for player 2.
#
# Given the pair of strategies $(\alpha, \beta)$, we can have the expected payoffs for two players. Denote $V^1(\alpha, \beta)$ and $V^2(\alpha, \beta)$ as the expected payoffs for two players respectively:
#
# $$
# \begin{aligned} V^{1}(\alpha, \beta) &=\alpha \beta r^1_{11}+\alpha(1-\beta) r^1_{12}+(1-\alpha) \beta r^1_{21}+(1-\alpha)(1-\beta) r^1_{22} \\ &=u^1 \alpha \beta+\alpha\left(r^1_{12}-r^1_{22}\right)+\beta\left(r^1_{21}-r^1_{22}\right)+r^1_{22} \end{aligned}
# $$
# $$
# \begin{aligned} V^{2}(\alpha, \beta) &=\alpha \beta r^2_{11}+\alpha(1-\beta) r^2_{12}+(1-\alpha) \beta r^2_{21}+(1-\alpha)(1-\beta) r^2_{22} \\ &=u^2 \alpha \beta+\alpha\left(r^2_{12}-r^2_{22}\right)+\beta\left(r^2_{21}-r^2_{22}\right)+r^2_{22}\end{aligned}
# $$
#
# where
#
# $$
# \begin{aligned} u^1 &=r^1_{11}-r^1_{12}-r^1_{21}+r^1_{22} \\ u^2 &=r^2_{11}-r^2_{12}-r^2_{21}+r^2_{22} .\end{aligned}
# $$
#
#
# """
#
# # %%
# """
# #### Set up matrix game (4 points)
#
#
# """
#
# # %%
# import numpy as np
# from copy import deepcopy
#
#
# def U(payoff):
# ########### TODO: Compute u (1 point) ###########
# u = payoff[0,0] - payoff[0,1] - payoff[1,0] + payoff[1,1]
# ########### END TODO ############################
# return u
#
#
# # expected payoff
# def V(alpha, beta, payoff):
# ########### TODO: Compute expected payoff of given strategies alpha and beta (1 point) ###########
# u = U(payoff)
# v = u*alpha*beta + alpha*(payoff[0,1]-payoff[1,1]) + beta*(payoff[1,0]-payoff[1,1]) + payoff[1,1]
# ########### END TODO ##############################################################################
# return v
#
#
# payoff_0 = np.array([[0, 3],
# [1, 2]])
# payoff_1 = np.array([[3, 2],
# [0, 1]])
#
# pi_alpha = 0. # init policy for player 1
# pi_beta = 0.9 # init policy for player 2
#
# ########### TODO:Give nash strategy of given matrix game (2 points) ###########
# pi_alpha_nash = 1/2 # nash strategy for player 1
# pi_beta_nash = 1/2 # nash strategy for player 2
# ########### END TODO ###############################################################
#
# u_alpha = U(payoff_0)
# u_beta = U(payoff_1)
#
# # %%
# assert math.isclose(U(payoff_0), -2)
# assert math.isclose(U(payoff_1), 2)
#
# assert math.isclose(V(alpha=0.2, beta=0.9, payoff=payoff_0), 47/50)
# assert math.isclose(V(alpha=0.6, beta=0.4, payoff=payoff_1), 42/25)
#
# # %%
# """
# #### Infinitesimal Gredient Ascent (IGA) (2 points)
#
# To find the optimal strategies, here we use the [Infinitesimal Gradient Ascent (IGA)](https://www.sciencedirect.com/science/article/pii/S0004370202001212) to adjust the strategies at each iteration by considering the effect of changing its strategy on its expected payoffs. These effects can be captured by calculating the partial derivatives of its expected payoff with respect to its strategy.
#
# $$
# \begin{aligned} \frac{\partial V^{1}(\alpha, \beta)}{\partial \alpha} &=\beta u^1+\left(r^1_{12}-r^1_{22}\right) \\ \frac{\partial V^{2}(\alpha, \beta)}{\partial \beta} &=\alpha u^2+\left(r^2_{21}-r^2_{22}\right). \end{aligned}
# $$
#
# According the gradient from partial derivatives, players could adjust the strategies in the direction of current gradient with some step size $\eta$. If $(\alpha_k, \beta_k)$ is the strategy pair at $k$th iteration, then using IGA update the strategies would get the new strategies:
#
# $$
# \begin{array}{l}{\alpha_{k+1}=\alpha_{k}+\eta \frac{\partial V^{1}\left(\alpha_{k}, \beta_{k}\right)}{\partial \alpha_{k}}} \\ {\beta_{k+1}=\beta_{k}+\eta \frac{\partial V^{2}\left(\alpha_{k}, \beta_{k}\right)}{\partial \beta_{k}}}\end{array}
# $$
# """
#
# # %%
# def IGA(pi_alpha,
# pi_beta,
# payoff_0,
# payoff_1,
# u_alpha,
# u_beta,
# iteration=1000, # iteration number
# eta=0.01 # step size
# ):
# pi_alpha_history = [pi_alpha]
# pi_beta_history = [pi_beta]
# pi_alpha_gradient_history = [0.]
# pi_beta_gradient_history = [0.]
# for i in range(iteration):
# ########### TODO:Implement IGA (2 points) ###########
# pi_alpha_gradient = pi_beta*u_alpha + (payoff_0[0, 1] - payoff_0[1, 1])
# pi_beta_gradient = pi_alpha*u_beta + (payoff_1[1, 0] - payoff_1[1, 1])
# pi_alpha_next = pi_alpha + eta*pi_alpha_gradient
# pi_beta_next = pi_beta + eta*pi_beta_gradient
# ########### END TODO ###############################
# pi_alpha = max(0., min(1., pi_alpha_next))
# pi_beta = max(0., min(1., pi_beta_next))
# pi_alpha_gradient_history.append(pi_alpha_gradient)
# pi_beta_gradient_history.append(pi_beta_gradient)
# pi_alpha_history.append(pi_alpha)
# pi_beta_history.append(pi_beta)
# return pi_alpha_history, \
# pi_beta_history, \
# pi_alpha_gradient_history, \
# pi_beta_gradient_history
#
# # %%
# """
# #### WoLF-IGA (2 points)
#
# The above IGA algorithm uses constant step size. A specific method for varying the learning rate here is [IGA WoLF (Win or Learn Fast)](https://www.sciencedirect.com/science/article/pii/S0004370202001212), it allows the step size varies over time. Let $\alpha^{e}$ and $\beta^{e}$ represent the equilibrium strategies of two players, now we have new updated rules for WoLF-IGA algorithm:
#
# $$
# \begin{array}{l}{\alpha_{k+1}=\alpha_{k}+\eta_k^{1} \frac{\partial V^{1}\left(\alpha_{k}, \beta_{k}\right)}{\partial \alpha_{k}}} \\ {\beta_{k+1}=\beta_{k}+\eta_k^{2} \frac{\partial V^{2}\left(\alpha_{k}, \beta_{k}\right)}{\partial \beta_{k}}}\end{array}
# $$
#
# where
#
# $$
# \eta_{k}^{1}=\left\{\begin{array}{l}{\eta_{\min } \text { if } V^1\left(\alpha_{k}, \beta_{k}\right)>V^1\left(\alpha^{e}, \beta_{k}\right)} \\ {\eta_{\max } \text { otherwise }}\end{array}\right.
# $$
# $$
# \eta_{k}^{2}=\left\{\begin{array}{l}{\eta_{\min } \text { if } V^2\left(\alpha_{k}, \beta_{k}\right)>V^2\left(\alpha_{k}, \beta^{e}\right)} \\ {\eta_{\max } \text { otherwise }}\end{array}\right.
# $$.
#
#
# """
#
# # %%
# def WoLF_IGA(pi_alpha,
# pi_beta,
# payoff_0,
# payoff_1,
# u_alpha,
# u_beta,
# pi_alpha_nash,
# pi_beta_nash,
# iteration=1000,
# eta_min=0.01, # min step size
# eta_max=0.04 # max step size
# ):
# pi_alpha_history = [pi_alpha]
# pi_beta_history = [pi_beta]
# pi_alpha_gradient_history = [0.]
# pi_beta_gradient_history = [0.]
# for i in range(iteration):
# ########### TODO:Implement WoLF-IGA (2 points) ###########
# pi_alpha_gradient = pi_beta*u_alpha + (payoff_0[0, 1] - payoff_0[1, 1])
# pi_beta_gradient = pi_alpha*u_beta + (payoff_1[1, 0] - payoff_1[1, 1])
#
# player_0_current_strategy_expected_payoff = V(alpha=pi_alpha, beta=pi_beta, payoff=payoff_0)
# player_0_equilibrium_strategy_expected_payoff = V(alpha=pi_alpha_nash, beta=pi_beta, payoff=payoff_0)
# player_0_is_winning = player_0_current_strategy_expected_payoff > player_0_equilibrium_strategy_expected_payoff
# eta_0 = eta_min if player_0_is_winning else eta_max
# pi_alpha_next = pi_alpha + eta_0*pi_alpha_gradient
#
# player_1_current_strategy_expected_payoff = V(alpha=pi_alpha, beta=pi_beta, payoff=payoff_1)
# player_1_equilibrium_strategy_expected_payoff = V(alpha=pi_alpha, beta=pi_beta_nash, payoff=payoff_1)
# player_1_is_winning = player_1_current_strategy_expected_payoff > player_1_equilibrium_strategy_expected_payoff
# eta_1 = eta_min if player_1_is_winning else eta_max
# pi_beta_next = pi_beta + eta_1*pi_beta_gradient
# ########### END TODO #####################################
# pi_alpha = max(0., min(1., pi_alpha_next))
# pi_beta = max(0., min(1., pi_beta_next))
# pi_alpha_gradient_history.append(pi_alpha_gradient)
# pi_beta_gradient_history.append(pi_beta_gradient)
# pi_alpha_history.append(pi_alpha)
# pi_beta_history.append(pi_beta)
# return pi_alpha_history, \
# pi_beta_history, \
# pi_alpha_gradient_history, \
# pi_beta_gradient_history
#
# # %%
# myboolean = False
# myvar = 'foo' if myboolean else 'foobar'
# print(myvar)
#
# # %%
# """
# #### IGA-PP (2 points)
#
# The IGA agent uses the gradient from other's current strategies to adjust its strategy. Suppose that one player knows the change direction of the other’s strategy,
# i.e., strategy derivative, in addition to its current strategy.
# Then the player can forecast the other’s strategy and adjust its strategy in response to the forecasted strategy. Thus the strategy update rules is changed to by using the policy prediction ([IGA-PP](https://www.aaai.org/ocs/index.php/AAAI/AAAI10/paper/view/1885)):
#
# $$
# \begin{array}{l}{\alpha_{k+1}=\alpha_{k}+\eta\frac{\partial V^{1}\left(\alpha_{k}, \beta_{k} + \gamma \partial_{\beta}V^{2}\left(\alpha_{k}, \beta_{k}\right) \right)}{\partial \alpha_{k}}} \\ {\beta_{k+1}=\beta_{k}+\eta \frac{\partial V^{2}\left(\alpha_{k} + \gamma \partial_{\alpha} V^{1}\left(\alpha_{k}, \beta_{k} \right) , \beta_{k}\right)}{\partial \beta_{k}}}\end{array}
# $$
# """
#
# # %%
# def IGA_PP(pi_alpha,
# pi_beta,
# payoff_0,
# payoff_1,
# u_alpha,
# u_beta,
# iteration=10000,
# eta=0.01, # step size
# gamma=0.01 # step size for policy prediction
# ):
# pi_alpha_history = [pi_alpha]
# pi_beta_history = [pi_beta]
# pi_alpha_gradient_history = [0.]
# pi_beta_gradient_history = [0.]
# for i in range(iteration):
# ########### TODO:Implement IGA-PP (2 points) ###########
# pi_beta_gradient_for_policy_prediction = pi_alpha*u_beta + (payoff_1[1, 0] - payoff_1[1, 1])
# predicted_pi_beta = pi_beta + gamma*pi_beta_gradient_for_policy_prediction
# pi_alpha_gradient = predicted_pi_beta*u_alpha + (payoff_0[0, 1] - payoff_0[1, 1])
#
# pi_alpha_gradient_for_policy_prediction = pi_beta*u_alpha + (payoff_0[0, 1] - payoff_0[1, 1])
# predicted_pi_alpha = pi_alpha + gamma*pi_alpha_gradient_for_policy_prediction
# pi_beta_gradient = predicted_pi_alpha*u_beta + (payoff_1[1, 0] - payoff_1[1, 1])
#
# pi_alpha_next = pi_alpha + eta*pi_alpha_gradient
# pi_beta_next = pi_beta + eta*pi_beta_gradient
# ########### END TODO ####################################
# pi_alpha = max(0., min(1., pi_alpha_next))
# pi_beta = max(0., min(1., pi_beta_next))
# pi_alpha_gradient_history.append(pi_alpha_gradient)
# pi_beta_gradient_history.append(pi_beta_gradient)
# pi_alpha_history.append(pi_alpha)
# pi_beta_history.append(pi_beta)
# return pi_alpha_history, \
# pi_beta_history, \
# pi_alpha_gradient_history, \
# pi_beta_gradient_history
#
# # %%
# """
# #### Run and compare different methods
# """
#
# # %%
# %matplotlib inline
# import matplotlib
# import matplotlib.pyplot as plt
#
# FONTSIZE = 12
#
# # Tool to plot the learning dynamics
# def plot_dynamics(history_pi_0, history_pi_1, pi_alpha_gradient_history, pi_beta_gradient_history, title=''):
# colors = range(len(history_pi_1))
# fig = plt.figure(figsize=(6, 5))
# ax = fig.add_subplot(111)
#
# scatter = ax.scatter(history_pi_0, history_pi_1, c=colors, s=1)
# ax.scatter(0.5, 0.5, c='r', s=15., marker='*')
# colorbar = fig.colorbar(scatter, ax=ax)
# colorbar.set_label('Iterations', rotation=270, fontsize=FONTSIZE)
#
# skip = slice(0, len(history_pi_0), 50)
# ax.quiver(history_pi_0[skip],
# history_pi_1[skip],
# pi_alpha_gradient_history[skip],
# pi_beta_gradient_history[skip],
# units='xy', scale=10., zorder=3, color='blue',
# width=0.007, headwidth=3., headlength=4.)
#
# ax.set_ylabel("Policy of Player 2", fontsize=FONTSIZE)
# ax.set_xlabel("Policy of Player 1", fontsize=FONTSIZE)
# ax.set_ylim(0, 1)
# ax.set_xlim(0, 1)
# ax.set_title(title, fontsize=FONTSIZE+8)
# plt.tight_layout()
# plt.show()
#
#
# # %%
# np.arange(1000)[slice(0, 200, 50)]
#
# # %%
# """
# We have set up the running code for three algorithms on given matrix game as below. You can run/validate and tune (e.g., try different parameters, observe the convergence and learning dynamics) the results by yourself.
# """
#
# # %%
# agents = ['IGA', 'WoLF-IGA', 'IGA-PP']
#
# for agent in agents:
#
# if agent == 'IGA':
# pi_alpha_history, \
# pi_beta_history, \
# pi_alpha_gradient_history, \
# pi_beta_gradient_history = IGA(pi_alpha,
# pi_beta,
# payoff_0,
# payoff_1,
# u_alpha,
# u_beta,
# iteration=1000, # iteration number
# eta=0.01 # step size
# )
# elif agent == 'WoLF-IGA':
# pi_alpha_history, \
# pi_beta_history, \
# pi_alpha_gradient_history, \
# pi_beta_gradient_history = WoLF_IGA(pi_alpha,
# pi_beta,
# payoff_0,
# payoff_1,
# u_alpha,
# u_beta,
# pi_alpha_nash=pi_alpha_nash,
# pi_beta_nash=pi_beta_nash,
# iteration=1000, # iteration number
# eta_min=0.01, # min step size
# eta_max=0.04 # max step size
# )
#
#
# elif agent == 'IGA-PP':
# pi_alpha_history, \
# pi_beta_history, \
# pi_alpha_gradient_history, \
# pi_beta_gradient_history = IGA_PP(pi_alpha,
# pi_beta,
# payoff_0,
# payoff_1,
# u_alpha,
# u_beta,
# iteration=10000, # iteration number
# eta=0.01, # step size
# gamma=0.01 # step size for policy prediction
# )
#
#
# plot_dynamics(pi_alpha_history,
# pi_beta_history,
# pi_alpha_gradient_history,
# pi_beta_gradient_history,
# agent)
# print('{} Done'.format(agent))
#
# # %%
# """
# ## Part II: Stochastic Game (10 points)
# """
#
# # %%
# """
# ### Problem Description
# """
#
# # %%
# """
# In this part, you are required to implement two agent to play the Stochastic Game, which has non-monotonicity reward and requires exploration to achieve the global optimal.
#
# There are $3$ intermediate states before arriving at the final state. The game transition and reward matrices are:
#
# ![Stochastic Game](https://raw.githubusercontent.com/mlii/mvrl/master/data/sg.png)
#
# Given an initial reward matrix (shown in the middle of the above plot), the choice of joint action leads to different branches. For example, the joint action pair (0, 0) will lead to the left branch, while the joint action pair (1, 1) will lead to the branch on the right. Agents can observe the current step number and branch. Zero rewards lead to the termination state (shown as the red cross).
#
# The optimal policy is to take the top left action pair (0, 0), and finally take the bottom right action pair (1, 1), resulting in a optimal total payoff of $8$.
#
# This game is not easy, because it needs $3$-step exploration to discover the optimal policy, and is hard to deviate from sub-optimal (the right branch). Thus, using a strategic exploration approach is necessary.
#
# """
#
# # %%
# import numpy as np
#
#
# class StochasticGame():
# def __init__(self, episode_limit=5, good_branches=2, batch_size=None, **kwargs):
# # Define the agents
# self.n_agents = 2
#
# self.episode_limit = episode_limit
#
# # Define the internal state
# self.steps = 0
#
# r_matrix = [[1,1],[1,1]]
# self.payoff_values = [r_matrix for _ in range(self.episode_limit)]
# self.final_step_diff =[[1,1],[1,4]]
#
# self.branches = 4
# self.branch = 0
#
# self.n_actions = len(self.payoff_values[0])
#
# self.good_branches = good_branches
#
# def reset(self):
# """ Returns initial observations and states"""
# self.steps = 0
# self.branch = 0
# return self.get_obs()
#
# def step(self, actions):
# """ Returns reward, terminated, info """
# current_branch = 0
# if (actions[0], actions[1]) == (0,0):
# current_branch = 0
# if (actions[0], actions[1]) == (0,1):
# current_branch = 1
# if (actions[0], actions[1]) == (1,0):
# current_branch = 2
# if (actions[0], actions[1]) == (1,1):
# current_branch = 3
#
# if self.steps == 0:
# self.branch = current_branch
#
# info = {}
#
# info["good_payoff"] = 0
# info["branch"] = self.branch
#
# if self.good_branches == 4:
# reward = 1 if self.branch == current_branch else 0 # Need to follow your branch
# elif self.good_branches == 2:
# reward = 1 if self.branch in [0,3] and self.branch == current_branch else 0
# else:
# raise Exception("Environment not setup to handle {} good branches".format(self.good_branches))
#
# if self.episode_limit > 1 and self.steps == self.episode_limit - 1 and self.branch == 0:
# info["good_payoff"] = 1
# reward = self.final_step_diff[actions[0]][actions[1]]
#
# self.steps += 1
#
# if self.steps < self.episode_limit and reward > 0:
# terminated = False
# else:
# terminated = True
#
# info["episode_limit"] = False
#
# # How often the joint-actions are taken
# info["action_00"] = 0
# info["action_01"] = 0
# info["action_10"] = 0
# info["action_11"] = 0
# if (actions[0], actions[1]) == (0, 0):
# info["action_00"] = 1
# if (actions[0], actions[1]) == (0, 1):
# info["action_01"] = 1
# if (actions[0], actions[1]) == (1, 0):
# info["action_10"] = 1
# if (actions[0], actions[1]) == (1, 1):
# info["action_11"] = 1
#
# return self.get_obs(), [reward] * 2, [terminated] * 2, info
#
# def get_obs(self):
# """ Returns all agent observations in a list """
# one_hot_step = [0] * (self.episode_limit + 1 + self.branches)
# one_hot_step[self.steps] = 1
# one_hot_step[self.episode_limit + 1 + self.branch] = 1
# return [tuple(one_hot_step) for _ in range(self.n_agents)]
#
# def get_obs_agent(self, agent_id):
# """ Returns observation for agent_id """
# return self.get_obs()[agent_id]
#
# def get_obs_size(self):
# """ Returns the shape of the observation """
# return len(self.get_obs_agent(0))
#
# def get_state(self):
# return self.get_obs_agent(0)
#
# def get_state_size(self):
# """ Returns the shape of the state"""
# return self.get_obs_size()
#
# def get_total_actions(self):
# """ Returns the total number of actions an agent could ever take """
# return self.n_actions
#
#
# # %%
# """
# ### Example: Random Policy
# """
#
# # %%
# """
# A simple agent using random policy is provided below.
# """
#
# # %%
# from collections import defaultdict
# from functools import partial
# from abc import ABCMeta, abstractmethod
# import random
#
# import numpy as np
#
# def sample(pi):
# return np.random.choice(pi.size, size=1, p=pi)[0]
#
# def normalize(pi):
# minprob = np.min(pi)
# if minprob < 0.0:
# pi -= minprob
# pi /= np.sum(pi)
#
# class BaseQAgent:
# def __init__(self, name, action_num=2, phi=0.01, gamma=0.95, episilon=0.1, **kwargs):
# self.name = name
# self.action_num = action_num
# self.episilon = episilon
# self.gamma = gamma
# self.phi = phi
# self.epoch = 0
# self.Q = None
# self.pi = defaultdict(partial(np.random.dirichlet, [1.0] * self.action_num))
#
# def done(self):
# pass
#
# def act(self, observation, exploration=False):
# if exploration and random.random() < self.episilon:
# return random.randint(0, self.action_num - 1)
# else:
# return sample(self.pi[observation])
#
# @abstractmethod
# def update(self, observation, action, reward, next_observation, done):
# pass
#
# @abstractmethod
# def update_policy(self, observation, action):
# pass
#
#
# # %%
# """
# ### TODO: Implement an agent using Q-Learning (3 points)
# """
#
# # %%
# """
# Q-Learning is a single agent learning algorithm for finding optimal policies in MDPs. The key updating rule is as follwings:
#
# $$
# Q(s, a) \leftarrow(1-\phi) Q(s, a)+\phi\left(r+\gamma V\left(s^{\prime}\right)\right)
# $$
#
# where,
# $$
# V(s)=\max\left(\left[Q(s, a)_{a \in \mathcal{A}}\right]\right)
# $$
# """
#
# # %%
# class QAgent(BaseQAgent):
# def __init__(self, **kwargs):
# super().__init__('QAgent', **kwargs)
# self.Q = defaultdict(partial(np.random.rand, self.action_num))
# self.R = defaultdict(partial(np.zeros, self.action_num))
# self.count_R = defaultdict(partial(np.zeros, self.action_num))
#
# def done(self):
# self.R.clear()
# self.count_R.clear()
#
# def update(self, observation, action, reward, next_observation, done):
# self.count_R[observation][action] += 1.0
# self.R[observation][action] += (reward - self.R[observation][action]) / self.count_R[observation][action]
#
# if done:
# ########### TODO:Implement Q-Learning (Q updating for termination) (1 point) ###########
# V = 0 # the quality of state s' is 0 because it is a terminal state
# self.Q[observation][action] = (1 - self.phi)*self.Q[observation][action] + self.phi*(reward + self.gamma*V)
# ########### END TODO #####################################################
# else:
# ########### TODO:Implement Q-Learning (Q updating) (1 point) ###########
# V = self.val(next_observation)
# self.Q[observation][action] = (1 - self.phi)*self.Q[observation][action] + self.phi*(reward + self.gamma*V)
# ########### END TODO #####################################################
# self.update_policy(observation, action)
# self.epoch += 1
#
# def val(self, observation):
# ########### TODO:Implement Q-Learning (V) (1 point) ###########
# Q_s = self.Q[observation]
# v = np.max(Q_s)
# ########### END TODO ##########################################
# return v
#
# def update_policy(self, observation, action):
# Q = self.Q[observation]
# self.pi[observation] = (Q == np.max(Q)).astype(np.double)
# self.pi[observation] = self.pi[observation] / np.sum(self.pi[observation])
#
# # %%
# """
# ### Test your Q agents on the Stochastic Game
# """
#
# # %%
# import numpy as np
# import matplotlib
# import matplotlib.pyplot as plt
# from copy import deepcopy
#
def rollout(env, agents, exploration=True, max_episode=30000, log_episode_interval=500, verbose=False):
history_reward = []
state_n = env.reset()
episode_reward = 0
episode_count = 0
recorded_episodes = []
recorded_episode_reward = []
while episode_count < max_episode:
actions = np.array([agent.act(state, exploration) for state, agent in zip(state_n, agents)])
next_state_n, reward_n, done_n, _ = env.step(actions)
episode_reward += np.mean(reward_n)
for j, (state, reward, next_state, done, agent) in enumerate(zip(state_n, reward_n, next_state_n, done_n, agents)):
agent.update(state, actions[j], reward, next_state, done)
state_n = next_state_n
if np.all(done_n):
state_n = env.reset()
history_reward.append(episode_reward)
episode_reward = 0
episode_count += 1
if episode_count % log_episode_interval == 0:
recorded_episodes.append(episode_count)
episodes_mean_reward = np.mean(history_reward)
recorded_episode_reward.append(episodes_mean_reward)
history_reward = []
if verbose:
print('Episodes {}, Reward {}'.format(episode_count, episodes_mean_reward))
return recorded_episodes, recorded_episode_reward
#
# # %%
# agent_num = 2
# action_num = 2
#
# runs = 10
# log_episode_interval = 500
# # store data for each run
# train_recorded_episodes_log = []
# train_recorded_episode_reward_log = []
# test_recorded_episode_reward_log = []
#
# for i in range(runs):
# ##################################### INITIALISATION ####################################
# agents = []
# env = StochasticGame()
# for i in range(agent_num):
# # agent = BaseQAgent(name='random', action_num=action_num)
# agent = QAgent(action_num=action_num)
# agents.append(agent)
#
# ####################################### TRAINING #######################################
# train_recorded_episodes, train_recorded_episode_reward = rollout(env=env,
# agents=agents,
# exploration=True,
# max_episode=30000,
# log_episode_interval=log_episode_interval)
# # store result for every run
# train_recorded_episodes_log.append(train_recorded_episodes)
# train_recorded_episode_reward_log.append(train_recorded_episode_reward)
#
# ####################################### TESTING #######################################
# test_recorded_episodes, test_recorded_episode_reward = rollout(env=env,
# agents=agents,
# exploration=False,
# max_episode=10,
# log_episode_interval=1)
# # store result for every run
# test_recorded_episode_reward_log.append(np.mean(test_recorded_episode_reward))
#
# # %%
# ####################################### TRAINING #######################################
#
# import seaborn as sns; sns.set()
# import pandas as pd
# fig = plt.figure(figsize=(9, 7))
# ax = fig.add_subplot(111)
# df_reward = pd.DataFrame(train_recorded_episode_reward_log).melt()
# sns.lineplot(ax=ax, x='variable', y='value', data=df_reward)
# ax.set_title(f"Train learning Curve for {runs} runs")
# ax.set_ylabel("Episodic Reward")
# ax.set_xlabel("Episodes * " + str(log_episode_interval))
# ax.legend(loc="lower right")
# plt.tight_layout()
# plt.show()
#
# ####################################### TESTING #######################################
# print(f'Test reward is (average over {runs} runs):', np.mean(test_recorded_episode_reward_log))
#
# # %%
# test_recorded_episode_reward_log
#
# # %%
# ####################################### TRAINING #######################################
# # different episodes returned every time so each learning curve shown separately
# fig = plt.figure(figsize=(9, 7))
# ax = fig.add_subplot(111)
#
# for i in range(runs):
# ax.plot(train_recorded_episodes_log[i], train_recorded_episode_reward_log[i], label=f'run {i}')
# ax.set_title(f"Train learning Curve for {runs} runs")
# ax.set_ylabel("Episodic Reward")
# ax.set_xlabel("Iterations")
# ax.legend(loc="lower right")
# plt.tight_layout()
# plt.show()
#
# ####################################### TESTING #######################################
# print(f'Test reward is (average over {runs} runs):', np.mean(test_recorded_episode_reward_log))
#
# # %%
# """
# ### TODO: Implement an Advanced Agent to solve the Stochastic Game (7 points)
# """
#
# # %%
# """
# Unless you are extremely lucky, the Q-learning agent implemented above is very hard to succeed in the Stochastic Game. In this part, you are required to implement a really cool agent to play the Stochastic Game.
#
# **Hint: You might want to use a strategic exploration approach.**
#
# Points will be given based on the performance of your algorithm, e.g., if the test reward of your algorithm is 6, you will be given 6/8*7=5.25 points, since the optimal payoff is 8.
# """
#
# # %%
# class CoolAgent(BaseQAgent):
# def __init__(self, temperature, **kwargs):
# super().__init__('CoolAgent', **kwargs)
# self.Q = defaultdict(partial(np.random.rand, self.action_num))
# self.temperature = temperature
#
# def done(self):
# pass
#
# def act(self, observation, exploration):
# """
# If we are not exploring, choose actions greedily.
# Args:
# observation:
# exploration:
#
# Returns:
#
# """
# if exploration:
# return sample(self.pi[observation])
# else:
# return np.argmax(self.pi[observation])
#
# @abstractmethod
# def update(self, observation, action, reward, next_observation, done):
# if done:
# V = 0 # the quality of state s' is 0 because it is a terminal state
# self.Q[observation][action] = (1 - self.phi)*self.Q[observation][action] + self.phi*(reward + self.gamma*V)
# else:
# V = self.val(next_observation)
# self.Q[observation][action] = (1 - self.phi)*self.Q[observation][action] + self.phi*(reward + self.gamma*V)
# self.update_policy(observation, action)
# self.epoch += 1
#
# def val(self, observation):
# Q_s = self.Q[observation]
# v = np.max(Q_s)
# return v
#
# @abstractmethod
# def update_policy(self, observation, action):
# """
# Use Boltzmann exploration.
# Args:
# observation:
# action:
#
# Returns: None.
#
# """
# Q = self.Q[observation]
# softmax = special.softmax(x=Q/self.temperature)
# self.pi[observation] = softmax
#
# # %%
# # Feel Free to write code here to train and tune your cool agents,
# # and assign the trained agents to cool_agents at the end
# # ########################################
# # TODO: Your cool agent training code #############
# agent_num = 2
# action_num = 2
#
# runs = 10
# cool_log_episode_interval = 500
# # store data for each run
# train_cool_recorded_episodes_log = []
# train_cool_recorded_episode_reward_log = []
# test_cool_recorded_episode_reward_log = []
# temperature = 2
#
# for i in range(runs):
# ##################################### INITIALISATION ####################################
# agents = []
# env = StochasticGame()
# for i in range(agent_num):
# agent = CoolAgent(action_num=action_num, temperature=temperature)
# agents.append(agent)
#
# ####################################### TRAINING #######################################
# train_cool_recorded_episodes, train_cool_recorded_episode_reward = rollout(env=env,
# agents=agents,
# exploration=True,
# max_episode=30000,
# log_episode_interval=cool_log_episode_interval)
# # store result for every run
# train_cool_recorded_episodes_log.append(train_cool_recorded_episodes)
# train_cool_recorded_episode_reward_log.append(train_cool_recorded_episode_reward)
#
# ####################################### TESTING #######################################
# cool_agents = agents
# # Cool agent evaluation code, please do not change
# cool_env = StochasticGame()
# test_cool_recorded_episodes, test_cool_recorded_episode_reward = rollout(env=cool_env,
# agents=cool_agents,
# exploration=False,
# max_episode=10,
# log_episode_interval=1)
# # store result for every run
# test_cool_recorded_episode_reward_log.append(np.mean(test_cool_recorded_episode_reward))
#
# # %%
# ####################################### TRAINING #######################################
# import seaborn as sns; sns.set()
# import pandas as pd
# fig = plt.figure(figsize=(9, 7))
# ax = fig.add_subplot(111)
# df_cool_reward = pd.DataFrame(train_cool_recorded_episode_reward_log).melt()
# sns.lineplot(ax=ax, x='variable', y='value', data=df_cool_reward)
# ax.set_title(f"Train learning Curve for {runs} runs")
# ax.set_ylabel("Episodic Reward")
# ax.set_xlabel("Episodes * " + str(cool_log_episode_interval))
# ax.legend(loc="lower right")
# plt.tight_layout()
# plt.show()
#
# print(f'Cool agent\'s test reward is (average over {runs} runs):', np.mean(test_cool_recorded_episode_reward_log))
#
#
# # %%
# ####################################### TRAINING #######################################
# # different episodes returned every time so each learning curve shown separately
# fig = plt.figure(figsize=(9, 7))
# ax = fig.add_subplot(111)
#
# for i in range(runs):
# ax.plot(train_cool_recorded_episodes_log[i], train_cool_recorded_episode_reward_log[i], label=f'run {i}')
# ax.set_title(f"Train learning Curve for {runs} runs")
# ax.set_ylabel("Episodic Reward")
# ax.set_xlabel("Iterations")
# ax.legend(loc="lower right")
# plt.tight_layout()
# plt.show()
#
# ####################################### TESTING #######################################
# print(f'Cool agent\'s test reward is (average over {runs} runs):', np.mean(test_cool_recorded_episode_reward_log))
#
# # %%
# test_cool_recorded_episode_reward_log
#
# # %%
# """
# Few words to analysis the results comparing to the Q Agent, and what you have did to improve the performance. (< 300 words)
#
# **Q-Agent problems**
#
# The epsilon-greedy exploration of the Q-Agent is not optimal. In epsilon-greedy, the agent only distinguishes between greedy and non-greedy actions. Therefore, the agent fails to pay more attention to non-greedy but potentially promising actions than non-greedy actions which the agent estimates to be largely sub-optimal.
#
# This makes it very easy to fall into local optima, such as taking the right branch.
#
# **Boltzmann agent solutions**
#
# I have used Boltzmann exploration to address this shortcoming. In Boltzmann exploration, the probability of choosing an action given a state is:
#
# $\pi_t(a|s) = \frac{exp(Q_t(s, a)/\tau)}{\sum_{b=1}^{k} exp(Q_t(s, b)/\tau)}$
#
# Where $\tau$ is the positive temperature parameter. A larger $\tau$ “flattens” the softmax distribution and promotes exploration. Whereas a smaller $\tau$ promotes greedy action selection. The temperature parameter can be annealed over time but in this specific game, it was sufficient to use a constant $\tau$. $\tau$ = 2 was chosen following a hyperparameter search.
#
# The softmax policy helps the agent avoid being trapped in suboptimal policies.
#
# **Comparing the results**
#
# From the train learning curve for the Q-Agent, one can see that the epsilon-greedy behaviour hinders exploration. The agent either gets stuck in a sub-optimal policy with a reward of 5, or luckily finds the optimal policy with a reward of 8. However, after this initial convergence, there is little chance for exploration (only run 2 manages to escape the local optimum, whereas run 8 and run 9 stay stuck).
#
# Conversely, for the train learning curve for the Boltzmann agent, one can see that the agent is exploring extensively for at least 15,000 episodes across all 10 runs. This increased exploration allows it to find the optimal policy with a reward of 8. When exploration=False during testing, the agent can greedily choose this optimal policy.
#
#
#
# """
#
# # %%
# """
# ## Part III: Cournot Duopoly (12 points)
#
# Cournot Duopoly is a classic static game that models the imperfect competition in which multiple firms compete in price and production to capture market share.
# Since the firms' actions are continuous variables, the game is a continuous action setting.
# It is a **nonzero-sum game** (neither team-based nor zero-sum) which represents a challenge for current MARL methods.
#
# Let $a_i\in [-A_i,A_i]$ represents the set of actions for agent $i\in\{1,2\ldots, N\}:=\mathcal{N}$,
# where $A_i\in \mathbb{R}_{>0}$.
# Each agent $i$'s reward (profit) is
# $$
# R_i(a_i,a_{-i})=g_i(a_i,a_{-i})+ w_i(a_i),
# $$
# where
# $
# \partial^{2} g_{i} / \partial a_{i}^{2}<0, \partial g_{i} / \partial a_{-i}<0
# $,and
# $\partial^{2} g_{i} / \partial a_{i} \partial a_{-i}<0
# $.
# Agents adopt Markov policies as
# $
# a_{i} = \pi_i(a_{-i}).
# $
#
# """
#
# # %%
# """
# #### TODO: Assume $N=2$, prove that policy $\pi_i$ is non-increasing. (5 points)
#
#
# """
#
# # %%
# """
# Your answer here.
# """
#