├── images
├── score.png
├── stabilization
├── agent-environment.png
├── Cartpole-Architecture.png
└── architecture_notebook.png
├── latex
├── images
│ ├── kaist.png
│ ├── plot_score.png
│ ├── architecture.png
│ ├── agent-environment.png
│ ├── kaist_round_logo.png
│ └── example_extracted_screen.png
├── references.bib
└── main.tex
├── save_model
├── policy_net_best1.pt
├── policy_net_best2.pt
├── policy_net_best3.pt
├── target_net_best1.pt
├── target_net_best2.pt
└── target_net_best3.pt
├── save_graph
└── Cartpole_Vision_Stop-142_LastEpNum-20.png
├── Studies_on_Model_Free_Control_of_Dynamical_Systems.pdf
├── .gitignore
├── README.md
├── cartpole_vision_v1.py
└── LICENSE
/images/score.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fedebotu/vision-cartpole-dqn/HEAD/images/score.png
--------------------------------------------------------------------------------
/images/stabilization:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fedebotu/vision-cartpole-dqn/HEAD/images/stabilization
--------------------------------------------------------------------------------
/latex/images/kaist.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fedebotu/vision-cartpole-dqn/HEAD/latex/images/kaist.png
--------------------------------------------------------------------------------
/latex/images/plot_score.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fedebotu/vision-cartpole-dqn/HEAD/latex/images/plot_score.png
--------------------------------------------------------------------------------
/images/agent-environment.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fedebotu/vision-cartpole-dqn/HEAD/images/agent-environment.png
--------------------------------------------------------------------------------
/latex/images/architecture.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fedebotu/vision-cartpole-dqn/HEAD/latex/images/architecture.png
--------------------------------------------------------------------------------
/images/Cartpole-Architecture.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fedebotu/vision-cartpole-dqn/HEAD/images/Cartpole-Architecture.png
--------------------------------------------------------------------------------
/images/architecture_notebook.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fedebotu/vision-cartpole-dqn/HEAD/images/architecture_notebook.png
--------------------------------------------------------------------------------
/save_model/policy_net_best1.pt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fedebotu/vision-cartpole-dqn/HEAD/save_model/policy_net_best1.pt
--------------------------------------------------------------------------------
/save_model/policy_net_best2.pt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fedebotu/vision-cartpole-dqn/HEAD/save_model/policy_net_best2.pt
--------------------------------------------------------------------------------
/save_model/policy_net_best3.pt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fedebotu/vision-cartpole-dqn/HEAD/save_model/policy_net_best3.pt
--------------------------------------------------------------------------------
/save_model/target_net_best1.pt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fedebotu/vision-cartpole-dqn/HEAD/save_model/target_net_best1.pt
--------------------------------------------------------------------------------
/save_model/target_net_best2.pt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fedebotu/vision-cartpole-dqn/HEAD/save_model/target_net_best2.pt
--------------------------------------------------------------------------------
/save_model/target_net_best3.pt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fedebotu/vision-cartpole-dqn/HEAD/save_model/target_net_best3.pt
--------------------------------------------------------------------------------
/latex/images/agent-environment.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fedebotu/vision-cartpole-dqn/HEAD/latex/images/agent-environment.png
--------------------------------------------------------------------------------
/latex/images/kaist_round_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fedebotu/vision-cartpole-dqn/HEAD/latex/images/kaist_round_logo.png
--------------------------------------------------------------------------------
/latex/images/example_extracted_screen.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fedebotu/vision-cartpole-dqn/HEAD/latex/images/example_extracted_screen.png
--------------------------------------------------------------------------------
/save_graph/Cartpole_Vision_Stop-142_LastEpNum-20.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fedebotu/vision-cartpole-dqn/HEAD/save_graph/Cartpole_Vision_Stop-142_LastEpNum-20.png
--------------------------------------------------------------------------------
/Studies_on_Model_Free_Control_of_Dynamical_Systems.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fedebotu/vision-cartpole-dqn/HEAD/Studies_on_Model_Free_Control_of_Dynamical_Systems.pdf
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | *.egg-info/
24 | .installed.cfg
25 | *.egg
26 | MANIFEST
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | nosetests.xml
45 | coverage.xml
46 | *.cover
47 | .hypothesis/
48 | .pytest_cache/
49 |
50 | # Translations
51 | *.mo
52 | *.pot
53 |
54 | # Django stuff:
55 | *.log
56 | local_settings.py
57 | db.sqlite3
58 |
59 | # Flask stuff:
60 | instance/
61 | .webassets-cache
62 |
63 | # Scrapy stuff:
64 | .scrapy
65 |
66 | # Sphinx documentation
67 | docs/_build/
68 |
69 | # PyBuilder
70 | target/
71 |
72 | # Jupyter Notebook
73 | .ipynb_checkpoints
74 |
75 | # pyenv
76 | .python-version
77 |
78 | # celery beat schedule file
79 | celerybeat-schedule
80 |
81 | # SageMath parsed files
82 | *.sage.py
83 |
84 | # Environments
85 | .env
86 | .venv
87 | env/
88 | venv/
89 | ENV/
90 | env.bak/
91 | venv.bak/
92 |
93 | # Spyder project settings
94 | .spyderproject
95 | .spyproject
96 |
97 | # Rope project settings
98 | .ropeproject
99 |
100 | # mkdocs documentation
101 | /site
102 |
103 | # mypy
104 | .mypy_cache/
105 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Vision-Based CartPole with DQN
2 |
3 |
4 |
5 |
6 |
7 | Implementation of the CartPole from OpenAI's Gym using only visual input
8 | for Reinforcement Learning control with Deep Q-Networks
9 |
10 |
11 |
12 |
13 |
14 | ***Author:*** Federico Berto
15 |
16 | Thesis Project for University of Bologna;
17 | Reinforcement Learning: a Preliminary Study on Vision-Based Control
18 |
19 | A special thanks goes to `Adam Paszke `_,
20 | for a first implementation of the DQN algorithm with vision input in
21 | the Cartpole-V0 environment from OpenAI Gym.
22 | `Gym website `__.
23 |
24 | The goal of this project is to design a control system for stabilizing a
25 | Cart and Pole using Deep Reinforcement Learning, having only images as
26 | control inputs. We implement the vision-based control using the DQN algorithm
27 | combined with Convolutional Neural Network for Q-values approximation.
28 |
29 |
30 |
31 |
32 |
33 | The last two frames of the Cartpole are used as input, cropped and processed
34 | before using them in the Neural Network. In order to stabilize the training,
35 | we use an experience replay buffer as shown in the paper "Playing Atari with
36 | Deep Reinforcement Learning:
37 | __.
38 |
39 | Besides, a target network to further stabilize the training process is used.
40 | make the training not converge, we set a threshold for stopping training
41 | when we detect stable improvements: this way we learn optimal behavior
42 | without saturation.
43 |
44 |
45 | ## Version 1
46 |
47 | This version is less polished and in a `.py` file.
48 | The GUI is a handy tool for saving and loading trained models, and also for
49 | training start/stop. Models and Graphs are saved in Vision_Carpole/save_model
50 | and Vision_Cartpole/save_graph respectively.
51 |
52 |
53 | ## Version 2
54 | This `.ipynb` (Jupyter Notebook) version is clearer and with a more stable training.
55 | The architecture is as following:
56 |
57 |
58 |
59 |
60 |
61 | You may find more information inside the PDF report too.
62 |
63 |
64 |
65 |
66 |
67 | Final score averaged over 6 runs mean ± std
68 |
69 | If you want to improve this project, your help is always welcome! 😄
70 |
71 |
72 |
--------------------------------------------------------------------------------
/latex/references.bib:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | @article{mnih2013playing,
5 | title={Playing atari with deep reinforcement learning},
6 | author={Mnih, Volodymyr and Kavukcuoglu, Koray and Silver, David and Graves, Alex and Antonoglou, Ioannis and Wierstra, Daan and Riedmiller, Martin},
7 | journal={arXiv preprint arXiv:1312.5602},
8 | year={2013}
9 | }
10 | @article{DBLP:journals/corr/PintoDSG17,
11 | author = {Lerrel Pinto and
12 | James Davidson and
13 | Rahul Sukthankar and
14 | Abhinav Gupta},
15 | title = {Robust Adversarial Reinforcement Learning},
16 | journal = {CoRR},
17 | volume = {abs/1703.02702},
18 | year = {2017},
19 | url = {http://arxiv.org/abs/1703.02702},
20 | archivePrefix = {arXiv},
21 | eprint = {1703.02702},
22 | timestamp = {Fri, 05 Apr 2019 07:29:46 +0200},
23 | biburl = {https://dblp.org/rec/journals/corr/PintoDSG17.bib},
24 | bibsource = {dblp computer science bibliography, https://dblp.org}
25 | }
26 | @inproceedings{NEURIPS2018_69386f6b,
27 | author = {Chen, Ricky T. Q. and Rubanova, Yulia and Bettencourt, Jesse and Duvenaud, David K},
28 | booktitle = {Advances in Neural Information Processing Systems},
29 | editor = {S. Bengio and H. Wallach and H. Larochelle and K. Grauman and N. Cesa-Bianchi and R. Garnett},
30 | pages = {6571--6583},
31 | publisher = {Curran Associates, Inc.},
32 | title = {Neural Ordinary Differential Equations},
33 | url = {https://proceedings.neurips.cc/paper/2018/file/69386f6bb1dfed68692a24c8686939b9-Paper.pdf},
34 | volume = {31},
35 | year = {2018}
36 | }
37 |
38 | @article{DBLP:journals/corr/abs-1903-00374,
39 | author = {Lukasz Kaiser and
40 | Mohammad Babaeizadeh and
41 | Piotr Milos and
42 | Blazej Osinski and
43 | Roy H. Campbell and
44 | Konrad Czechowski and
45 | Dumitru Erhan and
46 | Chelsea Finn and
47 | Piotr Kozakowski and
48 | Sergey Levine and
49 | Ryan Sepassi and
50 | George Tucker and
51 | Henryk Michalewski},
52 | title = {Model-Based Reinforcement Learning for Atari},
53 | journal = {CoRR},
54 | volume = {abs/1903.00374},
55 | year = {2019},
56 | url = {http://arxiv.org/abs/1903.00374},
57 | archivePrefix = {arXiv},
58 | eprint = {1903.00374},
59 | timestamp = {Sat, 30 Mar 2019 19:27:21 +0100},
60 | biburl = {https://dblp.org/rec/journals/corr/abs-1903-00374.bib},
61 | bibsource = {dblp computer science bibliography, https://dblp.org}
62 | }
63 | @misc{brockman2016openai,
64 | abstract = {OpenAI Gym is a toolkit for reinforcement learning research. It includes a
65 | growing collection of benchmark problems that expose a common interface, and a
66 | website where people can share their results and compare the performance of
67 | algorithms. This whitepaper discusses the components of OpenAI Gym and the
68 | design decisions that went into the software.},
69 | added-at = {2018-04-12T12:08:39.000+0200},
70 | author = {Brockman, Greg and Cheung, Vicki and Pettersson, Ludwig and Schneider, Jonas and Schulman, John and Tang, Jie and Zaremba, Wojciech},
71 | biburl = {https://www.bibsonomy.org/bibtex/2cdc8f927d6c8657ea82951a09e34161a/achakraborty},
72 | description = {[1606.01540] OpenAI Gym},
73 | interhash = {cfd0ba0b44eda9a3ca67480dfbf823a0},
74 | intrahash = {cdc8f927d6c8657ea82951a09e34161a},
75 | keywords = {2016 arxiv paper reinforcement-learning},
76 | note = {cite arxiv:1606.01540},
77 | timestamp = {2018-04-12T12:08:39.000+0200},
78 | title = {OpenAI Gym},
79 | url = {http://arxiv.org/abs/1606.01540},
80 | year = 2016
81 | }
82 |
83 |
84 |
85 | @article{Silver_2016,
86 | added-at = {2016-03-11T14:36:05.000+0100},
87 | author = {Silver, David and Huang, Aja and Maddison, Chris J. and Guez, Arthur and Sifre, Laurent and van den Driessche, George and Schrittwieser, Julian and Antonoglou, Ioannis and Panneershelvam, Veda and Lanctot, Marc and Dieleman, Sander and Grewe, Dominik and Nham, John and Kalchbrenner, Nal and Sutskever, Ilya and Lillicrap, Timothy and Leach, Madeleine and Kavukcuoglu, Koray and Graepel, Thore and Hassabis, Demis},
88 | biburl = {https://www.bibsonomy.org/bibtex/29e987f58d895c490144693139cbc90c7/ytyoun},
89 | doi = {10.1038/nature16961},
90 | interhash = {48430c7891aaf9fe2582faa8f5d076c1},
91 | intrahash = {9e987f58d895c490144693139cbc90c7},
92 | journal = {Nature},
93 | keywords = {baduk go google},
94 | month = jan,
95 | number = 7587,
96 | pages = {484--489},
97 | publisher = {Nature Publishing Group},
98 | timestamp = {2016-03-11T14:37:40.000+0100},
99 | title = {Mastering the Game of {Go} with Deep Neural Networks and Tree Search},
100 | volume = 529,
101 | year = 2016
102 | }
103 |
104 | @article{DBLP:journals/corr/abs-1912-03513,
105 | author = {Warren B. Powell},
106 | title = {From Reinforcement Learning to Optimal Control: {A} unified framework
107 | for sequential decisions},
108 | journal = {CoRR},
109 | volume = {abs/1912.03513},
110 | year = {2019},
111 | url = {http://arxiv.org/abs/1912.03513},
112 | archivePrefix = {arXiv},
113 | eprint = {1912.03513},
114 | timestamp = {Thu, 02 Jan 2020 18:08:18 +0100},
115 | biburl = {https://dblp.org/rec/journals/corr/abs-1912-03513.bib},
116 | bibsource = {dblp computer science bibliography, https://dblp.org}
117 | }
118 | @article{Starcraft,
119 | author = {Vinyals, Oriol and Babuschkin, Igor and Czarnecki, Wojciech and Mathieu, Michaël and Dudzik, Andrew and Chung, Junyoung and Choi, David and Powell, Richard and Ewalds, Timo and Georgiev, Petko and Oh, Junhyuk and Horgan, Dan and Kroiss, Manuel and Danihelka, Ivo and Huang, Aja and Sifre, Laurent and Cai, Trevor and Agapiou, John and Jaderberg, Max and Silver, David},
120 | year = {2019},
121 | month = {11},
122 | pages = {},
123 | title = {Grandmaster level in StarCraft II using multi-agent reinforcement learning},
124 | volume = {575},
125 | journal = {Nature},
126 | doi = {10.1038/s41586-019-1724-z}
127 | }
128 |
129 | @book{sutton1998introduction,
130 | title={Introduction to reinforcement learning},
131 | author={Sutton, Richard S and Barto, Andrew G and others},
132 | volume={2},
133 | number={4},
134 | year={1998},
135 | publisher={MIT press Cambridge}
136 | }
137 |
138 | @book{goodfellow2016deep,
139 | title={Deep learning},
140 | author={Goodfellow, Ian and Bengio, Yoshua and Courville, Aaron},
141 | year={2016},
142 | publisher={MIT press}
143 | }
144 |
145 | @article{barto1994reinforcement,
146 | title={Reinforcement learning control},
147 | author={Barto, Andrew G},
148 | journal={Current opinion in neurobiology},
149 | volume={4},
150 | number={6},
151 | pages={888--893},
152 | year={1994},
153 | publisher={Elsevier}
154 | }
155 |
156 | @article{vemulavision,
157 | title={Vision-based Deep Reinforcement Learning},
158 | author={Vemula, Anirudh and Dwibedi, Debidatta},
159 | year={2016}
160 | }
161 |
162 | @article{rastogi2017deep,
163 | title={Deep Reinforcement Learning for Bipedal Robots},
164 | author={Rastogi, Divyam},
165 | year={2017}
166 | }
167 |
168 | @inproceedings{lample2017playing,
169 | title={Playing FPS games with deep reinforcement learning},
170 | author={Lample, Guillaume and Chaplot, Devendra Singh},
171 | booktitle={Thirty-First AAAI Conference on Artificial Intelligence},
172 | year={2017}
173 | }
174 |
175 | @article{appiahplaying,
176 | title={Playing FlappyBird with Deep Reinforcement Learning},
177 | author={Appiah, Naveen and Vare, Sagar}
178 | }
179 |
180 | @article{arulkumaran2017deep,
181 | title={Deep reinforcement learning: A brief survey},
182 | author={Arulkumaran, Kai and Deisenroth, Marc Peter and Brundage, Miles and Bharath, Anil Anthony},
183 | journal={IEEE Signal Processing Magazine},
184 | volume={34},
185 | number={6},
186 | pages={26--38},
187 | year={2017},
188 | publisher={IEEE}
189 | }
190 |
191 | @inproceedings{quillen2018deep,
192 | title={Deep reinforcement learning for vision-based robotic grasping: A simulated comparative evaluation of off-policy methods},
193 | author={Quillen, Deirdre and Jang, Eric and Nachum, Ofir and Finn, Chelsea and Ibarz, Julian and Levine, Sergey},
194 | booktitle={2018 IEEE International Conference on Robotics and Automation (ICRA)},
195 | pages={6284--6291},
196 | year={2018},
197 | organization={IEEE}
198 | }
199 |
200 | @phdthesis{nichols2014reinforcement,
201 | title={Reinforcement learning in continuous state-and action-space},
202 | author={Nichols, Barry D},
203 | year={2014},
204 | school={University of Westminster}
205 | }
206 |
207 | @article{zhang2015towards,
208 | title={Towards vision-based deep reinforcement learning for robotic motion control},
209 | author={Zhang, Fangyi and Leitner, J{\"u}rgen and Milford, Michael and Upcroft, Ben and Corke, Peter},
210 | journal={arXiv preprint arXiv:1511.03791},
211 | year={2015}
212 | }
213 |
214 |
215 | @article{chen2018comparing,
216 | title={Comparing Deep Reinforcement Learning Methods for Engineering Applications},
217 | author={Chen, Shengnan},
218 | year={2018}
219 | }
220 |
221 | @inproceedings{gu2016continuous,
222 | title={Continuous deep q-learning with model-based acceleration},
223 | author={Gu, Shixiang and Lillicrap, Timothy and Sutskever, Ilya and Levine, Sergey},
224 | booktitle={International Conference on Machine Learning},
225 | pages={2829--2838},
226 | year={2016}
227 | }
228 |
229 | @phdthesis{hochlander2014deep,
230 | title={Deep Learning for Reinforcement Learning in Pacman},
231 | author={Hochl{\"a}nder, Aaron},
232 | year={2014}
233 | }
234 |
235 | @inproceedings{schulman2015trust,
236 | title={Trust region policy optimization},
237 | author={Schulman, John and Levine, Sergey and Abbeel, Pieter and Jordan, Michael and Moritz, Philipp},
238 | booktitle={International conference on machine learning},
239 | pages={1889--1897},
240 | year={2015}
241 | }
242 |
243 | @article{lillicrap2015continuous,
244 | title={Continuous control with deep reinforcement learning},
245 | author={Lillicrap, Timothy P and Hunt, Jonathan J and Pritzel, Alexander and Heess, Nicolas and Erez, Tom and Tassa, Yuval and Silver, David and Wierstra, Daan},
246 | journal={arXiv preprint arXiv:1509.02971},
247 | year={2015}
248 | }
249 |
250 | @article{metropolis1949monte,
251 | title={The monte carlo method},
252 | author={Metropolis, Nicholas and Ulam, Stanislaw},
253 | journal={Journal of the American statistical association},
254 | volume={44},
255 | number={247},
256 | pages={335--341},
257 | year={1949},
258 | publisher={Taylor \& Francis}
259 | }
260 |
261 | @book{bertsekas1995dynamic,
262 | title={Dynamic programming and optimal control},
263 | author={Bertsekas, Dimitri P and Bertsekas, Dimitri P and Bertsekas, Dimitri P and Bertsekas, Dimitri P},
264 | volume={1},
265 | number={2},
266 | year={1995},
267 | publisher={Athena scientific Belmont, MA}
268 | }
269 |
270 | @article{watkins1992q,
271 | title={Q-learning},
272 | author={Watkins, Christopher JCH and Dayan, Peter},
273 | journal={Machine learning},
274 | volume={8},
275 | number={3-4},
276 | pages={279--292},
277 | year={1992},
278 | publisher={Springer}
279 | }
280 |
281 | @inproceedings{nair2010rectified,
282 | title={Rectified linear units improve restricted boltzmann machines},
283 | author={Nair, Vinod and Hinton, Geoffrey E},
284 | booktitle={Proceedings of the 27th international conference on machine learning (ICML-10)},
285 | pages={807--814},
286 | year={2010}
287 | }
288 |
289 | @article{schaul2015prioritized,
290 | title={Prioritized experience replay},
291 | author={Schaul, Tom and Quan, John and Antonoglou, Ioannis and Silver, David},
292 | journal={arXiv preprint arXiv:1511.05952},
293 | year={2015}
294 | }
295 |
296 | @article{schulman2015high,
297 | title={High-dimensional continuous control using generalized advantage estimation},
298 | author={Schulman, John and Moritz, Philipp and Levine, Sergey and Jordan, Michael and Abbeel, Pieter},
299 | journal={arXiv preprint arXiv:1506.02438},
300 | year={2015}
301 | }
302 |
303 | @inproceedings{levine2013guided,
304 | title={Guided policy search},
305 | author={Levine, Sergey and Koltun, Vladlen},
306 | booktitle={International Conference on Machine Learning},
307 | pages={1--9},
308 | year={2013}
309 | }
310 |
311 | @inproceedings{konda2000actor,
312 | title={Actor-critic algorithms},
313 | author={Konda, Vijay R and Tsitsiklis, John N},
314 | booktitle={Advances in neural information processing systems},
315 | pages={1008--1014},
316 | year={2000}
317 | }
318 |
319 | @article{silver2017mastering,
320 | title={Mastering the game of go without human knowledge},
321 | author={Silver, David and Schrittwieser, Julian and Simonyan, Karen and Antonoglou, Ioannis and Huang, Aja and Guez, Arthur and Hubert, Thomas and Baker, Lucas and Lai, Matthew and Bolton, Adrian and others},
322 | journal={Nature},
323 | volume={550},
324 | number={7676},
325 | pages={354},
326 | year={2017},
327 | publisher={Nature Publishing Group}
328 | }
329 |
330 | @article{kingma2014adam,
331 | title={Adam: A method for stochastic optimization},
332 | author={Kingma, Diederik P and Ba, Jimmy},
333 | journal={arXiv preprint arXiv:1412.6980},
334 | year={2014}
335 | }
336 |
337 | @article{srivastava2014dropout,
338 | title={Dropout: a simple way to prevent neural networks from overfitting},
339 | author={Srivastava, Nitish and Hinton, Geoffrey and Krizhevsky, Alex and Sutskever, Ilya and Salakhutdinov, Ruslan},
340 | journal={The journal of machine learning research},
341 | volume={15},
342 | number={1},
343 | pages={1929--1958},
344 | year={2014},
345 | publisher={JMLR. org}
346 | }
347 |
348 | @inproceedings{hershey2007approximating,
349 | title={Approximating the Kullback Leibler divergence between Gaussian mixture models},
350 | author={Hershey, John R and Olsen, Peder A},
351 | booktitle={2007 IEEE International Conference on Acoustics, Speech and Signal Processing-ICASSP'07},
352 | volume={4},
353 | pages={IV--317},
354 | year={2007},
355 | organization={IEEE}
356 | }
357 |
358 | @article{DBLP:journals/corr/abs-1907-03098,
359 | author = {Elit Cenk Alp and
360 | Mehmet Serdar G{\"{u}}zel},
361 | title = {Playing Flappy Bird via Asynchronous Advantage Actor Critic Algorithm},
362 | journal = {CoRR},
363 | volume = {abs/1907.03098},
364 | year = {2019},
365 | url = {http://arxiv.org/abs/1907.03098},
366 | archivePrefix = {arXiv},
367 | eprint = {1907.03098},
368 | timestamp = {Wed, 17 Jul 2019 10:27:36 +0200},
369 | biburl = {https://dblp.org/rec/bib/journals/corr/abs-1907-03098},
370 | bibsource = {dblp computer science bibliography, https://dblp.org}
371 | }
372 |
373 |
374 | @article{DBLP:journals/corr/BabaeizadehFTCK16,
375 | author = {Mohammad Babaeizadeh and
376 | Iuri Frosio and
377 | Stephen Tyree and
378 | Jason Clemons and
379 | Jan Kautz},
380 | title = {{GA3C:} GPU-based {A3C} for Deep Reinforcement Learning},
381 | journal = {CoRR},
382 | volume = {abs/1611.06256},
383 | year = {2016},
384 | url = {http://arxiv.org/abs/1611.06256},
385 | archivePrefix = {arXiv},
386 | eprint = {1611.06256},
387 | timestamp = {Mon, 13 Aug 2018 16:48:01 +0200},
388 | biburl = {https://dblp.org/rec/bib/journals/corr/BabaeizadehFTCK16},
389 | bibsource = {dblp computer science bibliography, https://dblp.org}
390 | }
391 |
392 |
393 | @article{DBLP:journals/corr/HasseltGS15,
394 | author = {Hado van Hasselt and
395 | Arthur Guez and
396 | David Silver},
397 | title = {Deep Reinforcement Learning with Double Q-learning},
398 | journal = {CoRR},
399 | volume = {abs/1509.06461},
400 | year = {2015},
401 | url = {http://arxiv.org/abs/1509.06461},
402 | archivePrefix = {arXiv},
403 | eprint = {1509.06461},
404 | timestamp = {Mon, 13 Aug 2018 16:47:32 +0200},
405 | biburl = {https://dblp.org/rec/bib/journals/corr/HasseltGS15},
406 | bibsource = {dblp computer science bibliography, https://dblp.org}
407 | }
408 |
409 |
410 | @article{DBLP:journals/corr/abs-1903-06372,
411 | author = {Wesley Suttle and
412 | Zhuoran Yang and
413 | Kaiqing Zhang and
414 | Zhaoran Wang and
415 | Tamer Basar and
416 | Ji Liu},
417 | title = {A Multi-Agent Off-Policy Actor-Critic Algorithm for Distributed Reinforcement
418 | Learning},
419 | journal = {CoRR},
420 | volume = {abs/1903.06372},
421 | year = {2019},
422 | url = {http://arxiv.org/abs/1903.06372},
423 | archivePrefix = {arXiv},
424 | eprint = {1903.06372},
425 | timestamp = {Mon, 01 Apr 2019 14:07:37 +0200},
426 | biburl = {https://dblp.org/rec/bib/journals/corr/abs-1903-06372},
427 | bibsource = {dblp computer science bibliography, https://dblp.org}
428 | }
429 |
430 |
431 | @article{DBLP:journals/corr/WangBHMMKF16,
432 | author = {Ziyu Wang and
433 | Victor Bapst and
434 | Nicolas Heess and
435 | Volodymyr Mnih and
436 | R{\'{e}}mi Munos and
437 | Koray Kavukcuoglu and
438 | Nando de Freitas},
439 | title = {Sample Efficient Actor-Critic with Experience Replay},
440 | journal = {CoRR},
441 | volume = {abs/1611.01224},
442 | year = {2016},
443 | url = {http://arxiv.org/abs/1611.01224},
444 | archivePrefix = {arXiv},
445 | eprint = {1611.01224},
446 | timestamp = {Mon, 13 Aug 2018 16:48:29 +0200},
447 | biburl = {https://dblp.org/rec/bib/journals/corr/WangBHMMKF16},
448 | bibsource = {dblp computer science bibliography, https://dblp.org}
449 | }
450 |
451 | @article{DBLP:journals/corr/WangFL15,
452 | author = {Ziyu Wang and
453 | Nando de Freitas and
454 | Marc Lanctot},
455 | title = {Dueling Network Architectures for Deep Reinforcement Learning},
456 | journal = {CoRR},
457 | volume = {abs/1511.06581},
458 | year = {2015},
459 | url = {http://arxiv.org/abs/1511.06581},
460 | archivePrefix = {arXiv},
461 | eprint = {1511.06581},
462 | timestamp = {Mon, 13 Aug 2018 16:48:17 +0200},
463 | biburl = {https://dblp.org/rec/bib/journals/corr/WangFL15},
464 | bibsource = {dblp computer science bibliography, https://dblp.org}
465 | }
466 |
467 | @article{DBLP:journals/corr/MahsereciBLH17,
468 | author = {Maren Mahsereci and
469 | Lukas Balles and
470 | Christoph Lassner and
471 | Philipp Hennig},
472 | title = {Early Stopping without a Validation Set},
473 | journal = {CoRR},
474 | volume = {abs/1703.09580},
475 | year = {2017},
476 | url = {http://arxiv.org/abs/1703.09580},
477 | archivePrefix = {arXiv},
478 | eprint = {1703.09580},
479 | timestamp = {Mon, 13 Aug 2018 16:48:13 +0200},
480 | biburl = {https://dblp.org/rec/bib/journals/corr/MahsereciBLH17},
481 | bibsource = {dblp computer science bibliography, https://dblp.org}
482 | }
483 |
484 | @article{DBLP:journals/corr/MnihBMGLHSK16,
485 | author = {Volodymyr Mnih and
486 | Adri{\`{a}} Puigdom{\`{e}}nech Badia and
487 | Mehdi Mirza and
488 | Alex Graves and
489 | Timothy P. Lillicrap and
490 | Tim Harley and
491 | David Silver and
492 | Koray Kavukcuoglu},
493 | title = {Asynchronous Methods for Deep Reinforcement Learning},
494 | journal = {CoRR},
495 | volume = {abs/1602.01783},
496 | year = {2016},
497 | url = {http://arxiv.org/abs/1602.01783},
498 | archivePrefix = {arXiv},
499 | eprint = {1602.01783},
500 | timestamp = {Mon, 13 Aug 2018 16:47:40 +0200},
501 | biburl = {https://dblp.org/rec/bib/journals/corr/MnihBMGLHSK16},
502 | bibsource = {dblp computer science bibliography, https://dblp.org}
503 | }
--------------------------------------------------------------------------------
/cartpole_vision_v1.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | '''
3 |
4 | ***Author:*** Federico Berto
5 |
6 | ============= Thesis Project for University of Bologna =============
7 | Reinforcement Learning: a Preliminary Study on Vision-Based Control
8 |
9 | A special thanks goes to gi`Adam Paszke `_,
10 | for a first implementation of the DQN algorithm with vision input in
11 | the Cartpole-V0 environment from OpenAI Gym.
12 | `Gym website `__.
13 |
14 | The goal of this project is to design a control system for stabilizing a
15 | Cart and Pole using Deep Reinforcement Learning, having only images as
16 | control inputs. We implement the vision-based control using the DQN algorithm
17 | combined with Convolutional Neural Network for Q-values approximation.
18 |
19 | The last two frames of the Cartpole are used as input, cropped and processed
20 | before using them in the Neural Network. In order to stabilize the training,
21 | we use an experience replay buffer as shown in the paper "Playing Atari with
22 | Deep Reinforcement Learning:
23 | __.
24 |
25 | Besides, a target network to further stabilize the training process is used.
26 | make the training not converge, we set a threshold for stopping training
27 | when we detect stable improvements: this way we learn optimal behavior
28 | without saturation.
29 |
30 | The GUI is a handi tool for saving and loading trained models, and also for
31 | training start/stop. Models and Graphs are saved in Vision_Carpole/save_model
32 | and Vision_Cartpole/save_graph respectively.
33 |
34 | '''
35 |
36 | import gym
37 | import math
38 | import random
39 | import numpy as np
40 | import matplotlib
41 | import matplotlib.pyplot as plt
42 | from collections import namedtuple
43 | from itertools import count
44 | from PIL import Image
45 | import torch
46 | import torch.nn as nn
47 | import torch.optim as optim
48 | import torch.nn.functional as F
49 | import torchvision.transforms as T
50 | from collections import deque
51 | import tkinter
52 |
53 | ############ HYPERPARAMETERS ##############
54 |
55 | BATCH_SIZE = 128 # original = 128
56 | GAMMA = 0.999 # original = 0.999
57 | EPS_START = 0.9 # original = 0.9
58 | EPS_END = 0.05 # original = 0.05
59 | EPS_DECAY = 5000 # original = 200
60 | TARGET_UPDATE = 50 # original = 10
61 | MEMORY_SIZE = 100000 # original = 10000
62 | END_SCORE = 200 # 200 for Cartpole-v0
63 | TRAINING_STOP = 142 # threshold for training stop
64 | N_EPISODES = 50000 # total episodes to be run
65 | LAST_EPISODES_NUM = 20 # number of episodes for stopping training
66 | FRAMES = 2 # state is the number of last frames: the more frames,
67 | # the more the state is detailed (still Markovian)
68 | RESIZE_PIXELS = 60 # Downsample image to this number of pixels
69 |
70 | # ---- CONVOLUTIONAL NEURAL NETWORK ----
71 | HIDDEN_LAYER_1 = 16
72 | HIDDEN_LAYER_2 = 32
73 | HIDDEN_LAYER_3 = 32
74 | KERNEL_SIZE = 5 # original = 5
75 | STRIDE = 2 # original = 2
76 | # --------------------------------------
77 |
78 | GRAYSCALE = True # False is RGB
79 | LOAD_MODEL = False # If we want to load the model, Default= False
80 | USE_CUDA = False # If we want to use GPU (powerful one needed!)
81 | ############################################
82 |
83 | graph_name = 'Cartpole_Vision_Stop-' + str(TRAINING_STOP) + '_LastEpNum-' + str(LAST_EPISODES_NUM)
84 |
85 |
86 | # GUI for saving models with Tkinter
87 | FONT = "Fixedsys 12 bold" #GUI font
88 | save_command1, save_command2, save_command3 = 0, 0, 0
89 | load_command_1, load_command_2, load_command_3 = 0, 0, 0
90 | resume_command, stop_command = 0,0
91 | window = tkinter.Tk()
92 | window.lift()
93 | window.attributes("-topmost", True)
94 | window.title("DQN-Vision Manager")
95 | lbl = tkinter.Label(window, text="Manage training -->")
96 | lbl.grid(column=0, row=0)
97 |
98 | def clicked1():
99 | global save_command1
100 | lbl.configure(text="Model saved in slot 1!")
101 | save_command1 = True
102 | btn1 = tkinter.Button(window, text="Save 1", font= FONT, command=clicked1, bg= "gray")
103 | btn1.grid(column=1, row=0)
104 |
105 | def clicked2():
106 | global save_command2
107 | lbl.configure(text="Model saved in slot 2!")
108 | save_command2 = True
109 | btn2 = tkinter.Button(window, text="Save 2", font= FONT,command=clicked2, bg= "gray")
110 | btn2.grid(column=2, row=0)
111 |
112 | def clicked3():
113 | global save_command3
114 | lbl.configure(text="Model saved in slot 3!")
115 | save_command3 = True
116 | btn3 = tkinter.Button(window, text="Save Best", font= FONT, command=clicked3, bg= "gray")
117 | btn3.grid(column=3, row=0)
118 |
119 | def clicked_load1():
120 | global load_command_1
121 | lbl.configure(text="Model loaded from slot 1!")
122 | load_command_1 = True
123 | load_btn1 = tkinter.Button(window, text="Load 1", font= FONT, command=clicked_load1, bg= "blue")
124 | load_btn1.grid(column=1, row=1)
125 |
126 | def clicked_load2():
127 | global load_command_2
128 | lbl.configure(text="Model loaded from slot 2!")
129 | load_command_2 = True
130 | load_btn2 = tkinter.Button(window, text="Load 2", font= FONT, command=clicked_load2, bg= "blue")
131 | load_btn2.grid(column=2, row=1)
132 |
133 | def clicked_load3():
134 | global load_command_3
135 | lbl.configure(text="Model loaded from slot 3!")
136 | load_command_3 = True
137 | load_btn3 = tkinter.Button(window, text="Load Best", font= FONT, command=clicked_load3, bg= "blue")
138 | load_btn3.grid(column=3, row=1)
139 |
140 | def clicked_resume():
141 | global resume_command
142 | lbl.configure(text="Training resumed!")
143 | resume_command = True
144 | resume_btn = tkinter.Button(window, text="Resume Training", font= FONT, command=clicked_resume, bg= "green")
145 | resume_btn.grid(column=1, row=2)
146 |
147 | def clicked_stop():
148 | global stop_command
149 | lbl.configure(text="Training stopped!")
150 | stop_command = True
151 | stop_btn = tkinter.Button(window, text="Stop Training", font= FONT, command=clicked_stop, bg= "red")
152 | stop_btn.grid(column=3, row=2)
153 |
154 |
155 | # Settings for GRAYSCALE / RGB
156 | if GRAYSCALE == 0:
157 | resize = T.Compose([T.ToPILImage(),
158 | T.Resize(RESIZE_PIXELS, interpolation=Image.CUBIC),
159 | T.ToTensor()])
160 |
161 | nn_inputs = 3*FRAMES # number of channels for the nn
162 | else:
163 | resize = T.Compose([T.ToPILImage(),
164 | T.Resize(RESIZE_PIXELS, interpolation=Image.CUBIC),
165 | T.Grayscale(),
166 | T.ToTensor()])
167 | nn_inputs = FRAMES # number of channels for the nn
168 |
169 |
170 | stop_training = False
171 |
172 | env = gym.make('CartPole-v0').unwrapped
173 |
174 | # Set up matplotlib
175 | is_ipython = 'inline' in matplotlib.get_backend()
176 | if is_ipython:
177 | from IPython import display
178 |
179 | plt.ion()
180 |
181 | # If gpu is to be used
182 | device = torch.device("cuda" if (torch.cuda.is_available() and USE_CUDA) else "cpu")
183 |
184 | Transition = namedtuple('Transition',
185 | ('state', 'action', 'next_state', 'reward'))
186 |
187 | # Memory for Experience Replay
188 | class ReplayMemory(object):
189 |
190 | def __init__(self, capacity):
191 | self.capacity = capacity
192 | self.memory = []
193 | self.position = 0
194 |
195 | def push(self, *args):
196 | """Saves a transition."""
197 | if len(self.memory) < self.capacity:
198 | self.memory.append(None) # if we haven't reached full capacity, we append a new transition
199 | self.memory[self.position] = Transition(*args)
200 | self.position = (self.position + 1) % self.capacity # e.g if the capacity is 100, and our position is now 101, we don't append to
201 | # position 101 (impossible), but to position 1 (its remainder), overwriting old data
202 |
203 | def sample(self, batch_size):
204 | return random.sample(self.memory, batch_size)
205 |
206 | def __len__(self):
207 | return len(self.memory)
208 |
209 | # Build CNN
210 | class DQN(nn.Module):
211 |
212 | def __init__(self, h, w, outputs):
213 | super(DQN, self).__init__()
214 | self.conv1 = nn.Conv2d(nn_inputs, HIDDEN_LAYER_1, kernel_size=KERNEL_SIZE, stride=STRIDE)
215 | self.bn1 = nn.BatchNorm2d(HIDDEN_LAYER_1)
216 | self.conv2 = nn.Conv2d(HIDDEN_LAYER_1, HIDDEN_LAYER_2, kernel_size=KERNEL_SIZE, stride=STRIDE)
217 | self.bn2 = nn.BatchNorm2d(HIDDEN_LAYER_2)
218 | self.conv3 = nn.Conv2d(HIDDEN_LAYER_2, HIDDEN_LAYER_3, kernel_size=KERNEL_SIZE, stride=STRIDE)
219 | self.bn3 = nn.BatchNorm2d(HIDDEN_LAYER_3)
220 | # Number of Linear input connections depends on output of conv2d layers
221 | # and therefore the input image size, so compute it.
222 | def conv2d_size_out(size, kernel_size = 5, stride = 2):
223 | return (size - (kernel_size - 1) - 1) // stride + 1
224 | convw = conv2d_size_out(conv2d_size_out(conv2d_size_out(w)))
225 | convh = conv2d_size_out(conv2d_size_out(conv2d_size_out(h)))
226 | linear_input_size = convw * convh * 32
227 | nn.Dropout()
228 | self.head = nn.Linear(linear_input_size, outputs)
229 |
230 | # Called with either one element to determine next action, or a batch
231 | # during optimization. Returns tensor([[left0exp,right0exp]...]).
232 | def forward(self, x):
233 | x = F.relu(self.bn1(self.conv1(x)))
234 | x = F.relu(self.bn2(self.conv2(x)))
235 | x = F.relu(self.bn3(self.conv3(x)))
236 | return self.head(x.view(x.size(0), -1))
237 |
238 | # Cart location for centering image crop
239 | def get_cart_location(screen_width):
240 | world_width = env.x_threshold * 2
241 | scale = screen_width / world_width
242 | return int(env.state[0] * scale + screen_width / 2.0) # MIDDLE OF CART
243 |
244 | # Cropping, downsampling (and Grayscaling) image
245 | def get_screen():
246 | # Returned screen requested by gym is 400x600x3, but is sometimes larger
247 | # such as 800x1200x3. Transpose it into torch order (CHW).
248 | screen = env.render(mode='rgb_array').transpose((2, 0, 1))
249 | # Cart is in the lower half, so strip off the top and bottom of the screen
250 | _, screen_height, screen_width = screen.shape
251 | screen = screen[:, int(screen_height*0.4):int(screen_height * 0.8)]
252 | view_width = int(screen_width * 0.6)
253 | cart_location = get_cart_location(screen_width)
254 | if cart_location < view_width // 2:
255 | slice_range = slice(view_width)
256 | elif cart_location > (screen_width - view_width // 2):
257 | slice_range = slice(-view_width, None)
258 | else:
259 | slice_range = slice(cart_location - view_width // 2,
260 | cart_location + view_width // 2)
261 | # Strip off the edges, so that we have a square image centered on a cart
262 | screen = screen[:, :, slice_range]
263 | # Convert to float, rescale, convert to torch tensor
264 | # (this doesn't require a copy)
265 | screen = np.ascontiguousarray(screen, dtype=np.float32) / 255
266 | screen = torch.from_numpy(screen)
267 | # Resize, and add a batch dimension (BCHW)
268 | return resize(screen).unsqueeze(0).to(device)
269 |
270 |
271 | env.reset()
272 | plt.figure()
273 | if GRAYSCALE == 0:
274 | plt.imshow(get_screen().cpu().squeeze(0).permute(1, 2, 0).numpy(),
275 | interpolation='none')
276 | else:
277 | plt.imshow(get_screen().cpu().squeeze(0).permute(
278 | 1, 2, 0).numpy().squeeze(), cmap='gray')
279 | plt.title('Example extracted screen')
280 | plt.show()
281 |
282 |
283 |
284 |
285 | eps_threshold = 0.9 # original = 0.9
286 |
287 | init_screen = get_screen()
288 | _, _, screen_height, screen_width = init_screen.shape
289 | print("Screen height: ", screen_height," | Width: ", screen_width)
290 |
291 | # Get number of actions from gym action space
292 | n_actions = env.action_space.n
293 |
294 | policy_net = DQN(screen_height, screen_width, n_actions).to(device)
295 | target_net = DQN(screen_height, screen_width, n_actions).to(device)
296 | target_net.load_state_dict(policy_net.state_dict())
297 | target_net.eval()
298 |
299 | if LOAD_MODEL == True:
300 | policy_net_checkpoint = torch.load('save_model/policy_net_best3.pt') # best 3 is the default best
301 | target_net_checkpoint = torch.load('save_model/target_net_best3.pt')
302 | policy_net.load_state_dict(policy_net_checkpoint)
303 | target_net.load_state_dict(target_net_checkpoint)
304 | policy_net.eval()
305 | target_net.eval()
306 | stop_training = True # if we want to load, then we don't train the network anymore
307 |
308 | optimizer = optim.RMSprop(policy_net.parameters())
309 | memory = ReplayMemory(MEMORY_SIZE)
310 |
311 | steps_done = 0
312 |
313 | # Action selection , if stop training == True, only exploitation
314 | def select_action(state, stop_training):
315 | global steps_done
316 | sample = random.random()
317 | eps_threshold = EPS_END + (EPS_START - EPS_END) * \
318 | math.exp(-1. * steps_done / EPS_DECAY)
319 | steps_done += 1
320 | # print('Epsilon = ', eps_threshold, end='\n')
321 | if sample > eps_threshold or stop_training:
322 | with torch.no_grad():
323 | # t.max(1) will return largest column value of each row.
324 | # second column on max result is index of where max element was
325 | # found, so we pick action with the larger expected reward.
326 | return policy_net(state).max(1)[1].view(1, 1)
327 | else:
328 | return torch.tensor([[random.randrange(n_actions)]], device=device, dtype=torch.long)
329 |
330 |
331 | episode_durations = []
332 |
333 |
334 | # Plotting
335 | def plot_durations(score):
336 | plt.figure(2)
337 | plt.clf()
338 | durations_t = torch.tensor(episode_durations, dtype=torch.float)
339 | episode_number = len(durations_t)
340 | plt.title('Training...')
341 | plt.xlabel('Episode')
342 | plt.ylabel('Duration')
343 | plt.plot(durations_t.numpy(), label= 'Score')
344 | matplotlib.pyplot.hlines(195, 0, episode_number, colors='red', linestyles=':', label='Win Threshold')
345 | # Take 100 episode averages and plot them too
346 | if len(durations_t) >= 100:
347 | means = durations_t.unfold(0, 100, 1).mean(1).view(-1)
348 | last100_mean = means[episode_number -100].item()
349 | means = torch.cat((torch.zeros(99), means))
350 | plt.plot(means.numpy(), label= 'Last 100 mean')
351 | print('Episode: ', episode_number, ' | Score: ', score, '| Last 100 mean = ', last100_mean)
352 | plt.legend(loc='upper left')
353 | #plt.savefig('./save_graph/cartpole_dqn_vision_test.png') # for saving graph with latest 100 mean
354 | plt.pause(0.001) # pause a bit so that plots are updated
355 | plt.savefig('save_graph/' + graph_name)
356 | if is_ipython:
357 | display.clear_output(wait=True)
358 | display.display(plt.gcf())
359 |
360 | # Training
361 | def optimize_model():
362 | if len(memory) < BATCH_SIZE:
363 | return
364 | transitions = memory.sample(BATCH_SIZE)
365 | # Transpose the batch (see https://stackoverflow.com/a/19343/3343043 for
366 | # detailed explanation). This converts batch-array of Transitions
367 | # to Transition of batch-arrays.
368 | batch = Transition(*zip(*transitions))
369 |
370 | # Compute a mask of non-final states and concatenate the batch elements
371 | # (a final state would've been the one after which simulation ended)
372 | non_final_mask = torch.tensor(tuple(map(lambda s: s is not None,
373 | batch.next_state)), device=device, dtype=torch.uint8)
374 | non_final_next_states = torch.cat([s for s in batch.next_state
375 | if s is not None])
376 | # torch.cat concatenates tensor sequence
377 | state_batch = torch.cat(batch.state)
378 | action_batch = torch.cat(batch.action)
379 | reward_batch = torch.cat(batch.reward)
380 |
381 | # Compute Q(s_t, a) - the model computes Q(s_t), then we select the
382 | # columns of actions taken. These are the actions which would've been taken
383 | # for each batch state according to policy_net
384 | state_action_values = policy_net(state_batch).gather(1, action_batch)
385 |
386 | # Compute V(s_{t+1}) for all next states.
387 | # Expected values of actions for non_final_next_states are computed based
388 | # on the "older" target_net; selecting their best reward with max(1)[0].
389 | # This is merged based on the mask, such that we'll have either the expected
390 | # state value or 0 in case the state was final.
391 | next_state_values = torch.zeros(BATCH_SIZE, device=device)
392 | next_state_values[non_final_mask] = target_net(non_final_next_states).max(1)[0].detach()
393 | # Compute the expected Q values
394 | expected_state_action_values = (next_state_values * GAMMA) + reward_batch
395 |
396 | # Compute Huber loss
397 | loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1))
398 | plt.figure(2)
399 |
400 | # Optimize the model
401 | optimizer.zero_grad()
402 | loss.backward()
403 | for param in policy_net.parameters():
404 | param.grad.data.clamp_(-1, 1)
405 | optimizer.step()
406 |
407 | mean_last = deque([0] * LAST_EPISODES_NUM, LAST_EPISODES_NUM)
408 |
409 | # Button click checking
410 |
411 | def check_button():
412 | global save_command1
413 | global save_command2
414 | global save_command3
415 | global load_command_1
416 | global load_command_2
417 | global load_command_3
418 | global resume_command
419 | global stop_command
420 | global stop_training
421 |
422 | # Saving the weights
423 | if save_command1 == True:
424 | torch.save(policy_net.state_dict(), 'save_model/policy_net_best1.pt') # we save the trained policy model
425 | torch.save(target_net.state_dict(), 'save_model/target_net_best1.pt') # we save the trained target model
426 | save_command1 = False
427 | if save_command2 == True:
428 | torch.save(policy_net.state_dict(), 'save_model/policy_net_best2.pt') # we save the trained policy model
429 | torch.save(target_net.state_dict(), 'save_model/target_net_best2.pt') # we save the trained target model
430 | save_command2 = False
431 | if save_command3 == True:
432 | torch.save(policy_net.state_dict(), 'save_model/policy_net_best3.pt') # we save the trained policy model
433 | torch.save(target_net.state_dict(), 'save_model/target_net_best3.pt') # we save the trained target model
434 | save_command3 = False
435 | # Loading the Weights
436 | if load_command_1 or load_command_2 or load_command_3:
437 | if load_command_1:
438 | policy_net_checkpoint = torch.load('save_model/policy_net_best1.pt')
439 | target_net_checkpoint = torch.load('save_model/target_net_best1.pt')
440 | load_command_1 = False
441 | if load_command_2:
442 | policy_net_checkpoint = torch.load('save_model/policy_net_best2.pt')
443 | target_net_checkpoint = torch.load('save_model/target_net_best2.pt')
444 | load_command_2 = False
445 | if load_command_3:
446 | policy_net_checkpoint = torch.load('save_model/policy_net_best3.pt')
447 | target_net_checkpoint = torch.load('save_model/target_net_best3.pt')
448 | load_command_3 = False
449 |
450 | policy_net.load_state_dict(policy_net_checkpoint)
451 | target_net.load_state_dict(target_net_checkpoint)
452 | policy_net.eval()
453 | target_net.eval()
454 | stop_training = True # if we want to load, then we don't train the network anymore
455 |
456 | # Training Start/Stop
457 | if resume_command == True:
458 | stop_training = False
459 | resume_command = False
460 | if stop_command == True:
461 | stop_training = True
462 | stop_command = False
463 |
464 | window.attributes("-topmost", False)
465 |
466 |
467 | # MAIN LOOP
468 |
469 | for i_episode in range(N_EPISODES):
470 | # Initialize the environment and state
471 | env.reset()
472 | init_screen = get_screen()
473 | screens = deque([init_screen] * FRAMES, FRAMES)
474 | state = torch.cat(list(screens), dim=1)
475 |
476 | for t in count():
477 |
478 | # Select and perform an action
479 | action = select_action(state, stop_training)
480 | state_variables, _, done, _ = env.step(action.item())
481 |
482 | # Observe new state
483 | screens.append(get_screen())
484 | next_state = torch.cat(list(screens), dim=1) if not done else None
485 |
486 | # Reward modification for better stability
487 | x, x_dot, theta, theta_dot = state_variables
488 | r1 = (env.x_threshold - abs(x)) / env.x_threshold - 0.8
489 | r2 = (env.theta_threshold_radians - abs(theta)) / env.theta_threshold_radians - 0.5
490 | reward = r1 + r2
491 | reward = torch.tensor([reward], device=device)
492 | if t >= END_SCORE-1:
493 | reward = reward + 20
494 | done = 1
495 | else:
496 | if done:
497 | reward = reward - 20
498 |
499 | # Store the transition in memory
500 | memory.push(state, action, next_state, reward)
501 |
502 | # Move to the next state
503 | state = next_state
504 |
505 | # Perform one step of the optimization (on the target network)
506 | if done:
507 | check_button() # We check the GUI for inputs
508 | episode_durations.append(t + 1)
509 | plot_durations(t + 1)
510 | mean_last.append(t + 1)
511 | mean = 0
512 | for i in range(LAST_EPISODES_NUM):
513 | mean = mean_last[i] + mean
514 | mean = mean/LAST_EPISODES_NUM
515 | if mean < TRAINING_STOP and stop_training == False:
516 | optimize_model()
517 | else:
518 | stop_training = 1
519 | break
520 |
521 | # Update the target network, copying all weights and biases in DQN
522 | if i_episode % TARGET_UPDATE == 0:
523 | target_net.load_state_dict(policy_net.state_dict())
524 |
525 | print('Complete')
526 | env.render()
527 | env.close()
528 | plt.ioff()
529 | plt.show()
--------------------------------------------------------------------------------
/latex/main.tex:
--------------------------------------------------------------------------------
1 | \documentclass[11pt]{article}
2 | \usepackage[]{babel}
3 | \usepackage{natbib}
4 | \usepackage{url}
5 | \usepackage[utf8x]{inputenc}
6 | \usepackage{amsmath}
7 | \DeclareMathOperator*{\argmax}{argmax} % thin space, limits underneath in displays
8 | \DeclareMathOperator*{\argmin}{argmin} % thin space, limits underneath in displays
9 | \usepackage{graphicx}
10 | \graphicspath{{images/}}
11 | \usepackage{parskip}
12 | \usepackage{fancyhdr}
13 | \usepackage{vmargin}
14 | \usepackage{breqn} % Automatic equation breaker
15 | \usepackage{amssymb} %% <- for \square and \blacksquare
16 | \usepackage{breqn} % used for automatic equation breaking
17 | \newcommand{\QEDA}{\null\nobreak\hfill\ensuremath{\blacksquare}}%
18 | \newcommand{\QEDB}{\null\nobreak\hfill\ensuremath{\square}}%
19 | \newcommand{\smallspace}{\hspace{0.5cm}}
20 | \setcounter{secnumdepth}{0} % for avoiding the numbering
21 | \usepackage{hyperref} % to click and go to pointed place in the document
22 | \usepackage{tcolorbox} % if we want to use the boxes
23 | \usepackage{cancel} % for cool cancellations
24 | \newenvironment{sfemph}{\begin{sffamily}\begin{emph}}{\end{sffamily}\end{emph}}
25 | % the text inside the exercise setup will be emphasized
26 | \usepackage{xcolor} % Colored text
27 | \usepackage{minted} % For highlighting Python code
28 | \usepackage[ruled,vlined]{algorithm2e} % for algorithms
29 | \usepackage{biblatex} % bibliography
30 | \addbibresource{references.bib}
31 |
32 | % Set defaults for minted
33 | \setminted{frame=lines,
34 | framesep=2mm,
35 | baselinestretch=1.2,
36 | bgcolor=,
37 | fontsize=\footnotesize,
38 | linenos
39 | }
40 | \usepackage{comment} %for multiline commenting
41 |
42 |
43 |
44 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
45 | % MODIFY KAIST TEMPLATE DATA HERE
46 |
47 | \title{Studies on Model-Free Control of Dynamical Systems with Visual Feedback}
48 | \author{Federico Berto}
49 | \date{\today}
50 | \newcommand{\professor}{***}
51 | \newcommand{\studentid}{***}
52 | \newcommand{\coursename}{Optimal Control}
53 | \newcommand{\courseid}{***}
54 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
55 |
56 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
57 | \setmarginsrb{3 cm}{2.5 cm}{3 cm}{2.5 cm}{1 cm}{1.5 cm}{1 cm}{1.5 cm}
58 |
59 | \makeatletter
60 | \let\thetitle\@title
61 | \let\theauthor\@author
62 | \let\thedate\@date
63 | \makeatother
64 |
65 | \pagestyle{fancy}
66 | \fancyhf{}
67 | \renewcommand{\headrulewidth}{0.4pt}% Default \headrulewidth is 0.4pt
68 | %\renewcommand{\footrulewidth}{0.4pt}% Default \footrulewidth is 0pt
69 | \rhead{\theauthor}
70 | %\rhead{\includegraphics[width=1cm]{example-image-a}}
71 | \lhead{Optimal Control Report}
72 | \chead{\raisebox{-1ex}{\includegraphics[width = 3cm, shift down = 1cm]{kaist.png}}}
73 | \cfoot{Page \thepage}
74 |
75 | \begin{document}
76 |
77 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
78 |
79 | \begin{titlepage}
80 | \centering
81 | \textsc{\LARGE Korea Advanced Institute of Science \\ \smallskip and Technology}\\[1 cm] % University Name
82 | \includegraphics[scale = 0.18]{kaist_round_logo.png}\\[1.5 cm] % University Logo
83 | \textsc{\Large \coursename}\\[0.5 cm] % Course Code
84 | \rule{\linewidth}{0.2 mm} \\[0.4 cm]
85 | { \huge \bfseries {\thetitle}}\\
86 | \rule{\linewidth}{0.2 mm} \\[1.5 cm]
87 |
88 |
89 | \begin{minipage}{0.5\textwidth}
90 | \begin{flushleft} \large
91 | \emph{Professor:}\\
92 | \professor \\ [0.5cm]
93 | \emph{Course ID:}\\
94 | \courseid
95 | \end{flushleft}
96 | \end{minipage}~
97 | \begin{minipage}{0.4\textwidth}
98 |
99 | \begin{flushright} \large
100 | \emph{Student:} \\
101 | \theauthor \\[0.5cm]
102 | \emph{ID number:}\\
103 | \studentid \\
104 | \end{flushright}
105 |
106 | \end{minipage}\\[2 cm]
107 |
108 |
109 | %\thedate
110 |
111 |
112 |
113 | \end{titlepage}
114 |
115 | % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
116 |
117 | % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
118 | \begin{abstract}
119 | Modeling is well know to be one of the most difficult challenges when developing control systems: partial observability and disturbances in the control system can make the system unstable; especially considering the cases of complex and nonlinear ones. Model-free control is an alternative for solving control problems without the need to design a complex model in the first place: in particular, Reinforcement Learning has shown promising results in controlling nonlinear systems even when the state variables cannot be derived directly, such as in the case of a system in which sensors are unavailable or broken. The goal of this report is to demonstrate the ability of Deep Q-Network algorithm in controlling a dynamical system with the aim of stabilizing an inverted pendulum using only raw pixels as state feedback: this model-free formulation does not require any assumption or previous knowledge of the dynamical system unlike most controllers.
120 |
121 | \end{abstract}
122 |
123 |
124 | \section{Introduction}
125 |
126 | Reinforcement Learning \cite{sutton1998introduction} is one of the branches of Machine Learning which has seen a surge in interest in recent years because of its ability to handle complex tasks with minimal human intervention and, in the case of model-free reinforcement learning, to learn a representation of the state-action space without needing the actual space variables.\\
127 | Reinforcement Learning (RL) has been successfully used for playing complex Atari games \cite{mnih2013playing}, for mastering the game of GO \cite{Silver_2016} and even Starcraft II \cite{Starcraft}, showing important results regarding high-dimensional state-action spaces.\\
128 | Another interesting application is the model-free control, which is still an open research topic \cite{DBLP:journals/corr/abs-1912-03513} given the complex nature of the continuous state: we will explore this setup in the report and show its promising capabilities in handling non-linear systems without the need of an explicit model formulation, unlike many controllers do. \\
129 | Moreover, we will show that the performance of the controller is better, to the best of the author's knowledge, than other similar setups of the raw-pixels based inverted pendulum thanks to some tweaks we will explore.
130 |
131 | \section{Brief Overview of Reinforcement Learning}
132 | The control system can be defined as in the Figure \ref{fig:agentenvironment}, usually called the \textit{agent-environment interface}, which is the correspondent of the controller-plant interface in classical control. This framework can be defined by the following:
133 |
134 | \begin{figure}[h]
135 | \centering
136 | \includegraphics[width=12cm]{agent-environment.png}
137 | \caption{Agent-Environment interface for the inverted pendulum system. $\pi^*_{ \{ a \mid s \} }$ denotes the optimal policy}
138 | \label{fig:agentenvironment}
139 | \end{figure}
140 |
141 | \begin{itemize}
142 | \item \textit{Policy}: set of \textit{actions} (which are the control inputs in the Optimal Control field) to be selected given the current state.
143 | \item \textit{Reward}: a scalar value to be maximized by the agent. This value is another feedback along with the state at each time step; this is usually set as a positive number if the agent is performing as desired and as a negative number otherwise. In the Optimal Control terms, it is equivalent to the opposite of the cost function.
144 | \item \textit{Value function}: whereas the reward defines what is good in a short time, the value function defines what is good in the long run; it is defined as the sum of the discounted future rewards that can be accumulated from a particular state.
145 | \end{itemize}
146 |
147 | The goal of the control system (agent) is to maximize the cumulative discounted reward defined as following from the environment:
148 |
149 | \begin{equation}
150 | G_t = R_{t+1} + \gamma R_{t+2} + ... = \sum_{k=0}^{\infty}\gamma^k R_{t+k+1}
151 | \end{equation}
152 | where $\gamma \in [0,1]$ is a discount factor used for giving a lighter weight to far-away future rewards. \\
153 | The policy $\pi$ choosing the actions leading to the highest reward can be chosen for the Deep Q-Networks in the \textit{$\varepsilon$-greedy} way:
154 | \begin{equation}
155 | \pi(a|s) = \begin{cases}
156 | 1 - \varepsilon, & \text{if $a = \argmax_{a \in \mathcal{A}} \, q^*(s,a)$}\\
157 | \varepsilon, & \text{a random action}.
158 | \end{cases}
159 | \end{equation}
160 | where $q^*(s,a)$ denotes the \textit{state-action value} and $\varepsilon$ is chosen depending on how much \textit{exploration} (randomly trying new actions for finding out undiscovered and possibly better states and actions) and \textit{exploitation} (choosing the known best action) ration we want the system to have.
161 |
162 | \paragraph{Trajectories of the system}
163 | In order to optimize the system, we need to know what trajectories lead to the best cumulative reward. In this setup, \textit{agent} is the entity acting on the \textit{environment}, that given a $state \ S_t \in \mathcal{S}$ selects one or more $actions \ A_t \in \mathcal{A}$ for interacting with the environment. Our agent then gets feedback from the environment itself: it gets a scalar valued $reward \ R_{t+1} \in \mathcal{R}$, and gets in a new state $S_{t+1} \in \mathcal{S}$. In a \textit{finite} Markov Decision Process the set of states, actions and rewards ($\mathcal{S},\mathcal{A},\mathcal{R})$ contains a finite number of elements; nonetheless, the problem can be extended in the continuous case. The agent-environment feedback loop repeats over time and it is updated at each time \textit{step}: action selection, state and reward signals are sent only at specific moments in time (t = 0,1,2,3...). The sequence of actions, states and rewards defines a \textit{trajectory} in time that can be described as:
164 | \begin{equation}
165 | S_0, A_0, R_1, S_1, A_1, R_2, S_2, A_2, R_3...
166 | \end{equation}
167 | This sequence can be used on the go for optimizing the system or stored in a buffer and used later in randomized batches allowing for better stability of the training.
168 |
169 |
170 | \section{Experimental Setup}
171 |
172 | We will conduct the experiments with the inverted pendulum simulation from OpenAI Gym \cite{brockman2016openai}. Also known as the \textit{cart-pole}, the inverted pendulum is a common benchmark for testing control systems because of its relative simplicity and yet challenging feat because of the system's nonlinearities. This system can be controlled with well-known controllers, such as the Linear Quadratic Regulator for the linearized version, or with i.e. the Model Predictive Control for the non-linear version, such as for the pendulum swing up; however, our task is more challenging because of the absence of the system's model.
173 |
174 | \begin{table}
175 | \centering
176 | \begin{tabular}{ |p{2cm}|p{4cm}|p{2cm}|p{2cm}| }
177 | \hline
178 | \multicolumn{4}{|c|}{Observation Space} \\
179 | \hline
180 | Num & Observation & Min & Max \\
181 | \hline
182 | 0 & Cart Position & -2.4 & 2.4 \\
183 | 1 & Cart Velocity & $-\infty$ & $+\infty$ \\
184 | 2 & Pole Angle & $\-41.8$\textdegree & $41.8$\textdegree \\
185 | 3 & Pole Angular Velocity & $-\infty$ & $\infty$ \\
186 | \hline
187 | \end{tabular}
188 | \label{table:tableenvironment}
189 | \caption{Inverted Pendulum's observation space}
190 | \end{table}
191 |
192 | \paragraph{The observations space} The simulation is made of a four dimensional observation space of the cart position, cart velocity, pole angle, and pole angular velocity as shown in Table \ref{table:tableenvironment}.
193 |
194 | The available actions are two discrete ones: push a cart left or right. The reward is defined as +1 for every time step the inverted pendulum stands including the termination step. The task is considered achieved when the average reward of the last 100 episodes reaches a score close to the maximum score of 200. Episode termination occurs when:
195 |
196 | \begin{itemize}
197 | \item The pole angle is more than $\pm 12$\textdegree
198 | \item The cart position is more than $\pm 2.4$ (i.e. the center of the cart almost reaches the edge of the display)
199 | \item The episode length is greater than 200
200 | \end{itemize}
201 |
202 | Although the observation space is fixed for the simulation, our vision-based control is based on a set of images of the simulation, which significantly increase the state observation size. In order to let the algorithm derive a good approximation of the state, we will use a sequence of the last $N$ images (i.e., the last 2 frames) for making it capable to infer the dynamics of the pendulum.
203 |
204 | \paragraph{The Algorithm: Deep Q-Learning}
205 |
206 | The Deep Q-Learning algorithm has shown state-of-the-art performance in multiple frameworks, such as the Atari framework \cite{mnih2013playing}.
207 | In order to approximate the action-value function, we will employ a Convolutional Neural Network $Q(s,a; \theta) \approx Q^*(s,a)$. For our purposes, $\theta$ will denote the set of weights of the network, which we will refer to as Q-network. A Q-network can be trained by minimizing a sequence of loss functions $L_i(\theta_i)$ changing at each iteration i,
208 |
209 | \begin{equation}
210 | L_i(\theta_i) = \mathbb{E}_{s,a \sim \rho(\cdot)}[\left(y_i - Q(s,a;\theta_i)\right)^2],
211 | \label{eq:lossfunction}
212 | \end{equation}
213 |
214 | where $y_i = \mathbb{E}_{s' \sim \mathcal{E}} [r + \gamma \max_{a'}Q(s', \theta_{i-1}) | s,a]$ is the target for iteration $i$, $\rho(s,a)$ is a probability distribution over sequences $s$ and actions $a$. The parameters from the previous iteration $\theta_{i-1}$ are kept fixed when optimizing the loss function $L_i(\theta_i)$. The targets depend on the network weights: for this reason, it differs from classical weights used in supervised learning, which are fixed before learning itself begins.
215 | \medskip
216 |
217 | \indent Since we want to minimize the loss function for obtaining a better fit of the networks with respect to the real action value function, we want to compute the gradient with respect to the weights:
218 |
219 | \begin{equation}
220 | \nabla_{\theta_i}L_i (\theta_i) = \mathbb{E}_{s,a \sim \rho(\cdot); s' \sim \mathcal(E)} [(r + \gamma \max_{a'} Q (s', a'; \theta_{i-1}) - Q(s,a; \theta_i)) \nabla_{\theta_i} Q(s,a; \theta_i)]
221 | \label{eq:gradientloss}
222 | \end{equation}
223 |
224 | The loss function is then minimized by either using stochastic gradient descent or more sophisticated methods like RMSprop. The behavior policy is $\epsilon$-greedy for ensuring sufficient exploration.
225 | \medskip
226 |
227 | \indent What makes the algorithm work is a technique known as \textit{experience replay}\cite{schaul2015prioritized}, by which we store the agent's experiences (also referred to as transitions) at each time-step, $e_t = (s_t, a_t, r_t, s_{t+1})$, in a data set $ \mathcal{D} = (e_1, ..., e_N)$, pooled over many episodes into a \textit{replay memory}. In the inner loop of our algorithm we apply Q-Learning updates, or mini-batch updates, to samples of experience, $e \sim \mathcal{D}$, picked up randomly from the pool of stored samples. After performing experience replay, the agent executes an action according to an $\epsilon$-greedy policy. Deep Q-Learning with experience replay is written in pseudo-code in Algorithm \ref{alg:DQN}.
228 | \begin{algorithm}[h]
229 | \caption{Deep Q-Learning with Experience Replay}
230 | \label{alg:DQN}
231 | \SetAlgoLined
232 | \DontPrintSemicolon
233 | Initialize replay memory $\mathcal{D}$ \;
234 | Initialize action value function Q with random weights \;
235 | \Repeat{terminated}{
236 | Observe initial state $s_1$\;
237 | \For{t=1: T}{
238 | Select an action $a_1$ using policy derived from Q (e.g. $\epsilon$-greedy)\;
239 | Carry out action $a_t$\;
240 | Observe reward $r_t$ and new state $s_{t+1}$\;
241 | Store transition $(s_t, a_t, r_t, s_{t+1})$ in replay buffer $\mathcal{D}$\;
242 | Sample random transitions $(s_j, a_j, r_j, s_{j+1})$ from $\mathcal{D}$\;
243 | Calculate target for each transition \;
244 | % MATCH SYNTAXXX!! LIKE s'
245 |
246 | \begin{equation}
247 | \text{Set } y_i = \begin{cases}
248 | r_j & \text{if } s_{j+1} \text{ is terminal}\\
249 | r_j + \gamma \max_{a'} Q(s_{j+1},a';\theta) & \text{if } s_{j+1} \text{ is non-terminal}
250 | \end{cases}
251 | \end{equation}
252 |
253 | Train the Q network on $(y_j - Q(s_j, a_j; \theta))^2$ using Equation \ref{eq:gradientloss}
254 | }
255 | }
256 | \end{algorithm}
257 |
258 | The following is the Python code for the experience replay, which is of paramount importance for decoupling time-dependent transitions which would introduce a bias in the system:
259 | \begin{minted}{python}
260 | class ReplayMemory(object):
261 | """Replay Memory class for storing system's trajectories"""
262 | def __init__(self, capacity):
263 | self.capacity = capacity
264 | self.memory = []
265 | self.position = 0
266 |
267 | def push(self, *args):
268 | """Saves a transition."""
269 | if len(self.memory) < self.capacity:
270 | self.memory.append(None) # if we haven't reached full
271 | # capacity, we append a new transition
272 | self.memory[self.position] = Transition(*args)
273 | self.position = (self.position + 1) % self.capacity # e.g if the capacity
274 | # is 100, and our position is now 101, we don't append to position 101
275 | # (impossible), but to position 1 (its remainder), overwriting old data
276 |
277 | def sample(self, batch_size):
278 | return random.sample(self.memory, batch_size)
279 |
280 | def __len__(self):
281 | return len(self.memory)
282 | \end{minted}
283 | Deep Q-Learning has several advantages by using experience replay. Firstly, since each step of experience is potentially used in many weight updates, we have a greater data efficiency. Secondly, randomizing the samples allows for improved efficiency and reduces the updates variance, given that learning directly from consecutive samples of experience is inefficient due to the strong correlations between the samples. Thirdly, by learning off-policy we may be able to avoid dangerous unwanted feedback loops. For example, if we did train on-policy, if the maximizing action were to move on the left then the training samples would be dominated by samples from the left-hand side; if the maximizing action were the opposite one on the right, the same would happen with the right-hand side samples. This behavior could lead to unwanted outcomes, like getting stuck in a poor local minimum, or even catastrophically diverge. Thus, by using the off-policy experience replay we are able to smooth out learning and to avoid oscillation or divergence in the parameters.
284 |
285 |
286 |
287 | \\
288 | The exploration and exploitation problem is dealt with by the use of the following $\varepsilon_{threshold}$, which decays over time; a lower threshold will result in higher exploitation of the learned optimal known actions:
289 |
290 | \begin{equation}
291 | \varepsilon_{threshold} = \varepsilon_{final} + (\varepsilon_{initial}-\varepsilon_{final})e^{-t/\varepsilon_{decay}}
292 | \end{equation}
293 |
294 | % \indent As regard the other two parameters, the \textit{kernel size} is the size of the square filter actuating convolution over the inputs (i.e. in our implementation we have a 5x5 filter). The second parameter, the \textit{stride}, is the number of pixels which are "skipped" each time while making the filter convolve. A higher stride will make the model less precise, but slower in learning; a $stride = 2$ is usually chosen because has been empirically proven to be the best choice for CNNs.
295 |
296 |
297 | \section{Towards Vision-Based Control}
298 |
299 | The first steps in trying to solve the inverted pendulum problem with raw pixels were based on a first implementation from Adam Paszke\footnote{\href{https://pytorch.org/tutorials/intermediate/reinforcement_q_learning.html}{Source: pytorch.org}}. The algorithm is based on Convolutional Neural Networks for predicting Q-values and implements basically the same structure of DQN.\\
300 | Although this implementation was showing improvements in training, no matter how much training the system received, the mean reward was always swinging up and down and showing no sign of convergence or divergence. In particular, after some tenths of episodes showing an abrupt improvement in performance there were several episodes in which the agent "forgot" about the previous experiences, suddenly decreasing the performance. The problem that needs to be solved is the overfitting of the Convolutional Neural Network, which overestimated the state-action values leading to a sub-optimal policy.
301 |
302 | \subsection{Dealing with Overfitting}
303 |
304 | % As regards the overfitting problem there are a couple of tweaks to prevent it from happening at all. First of all, we implement a \textit{Dropout}\footnote{Dropout\cite{srivastava2014dropout} is a method by which some neural network neurons are switched off during training with a probability $p_i$, hence "dropped-out". During the testing phase, all the neurons are switched on with their output multiplied by a weight $p_i$. This method has proven to make neural networks more stable and robust.} regularization for improving the network stability. However, this has little effect in the training process, because of the intrinsic problem of learning, forgetting and learning again.
305 | \paragraph{Improving Image Pre-Processing}
306 | One first steps of state observation improvement implies simplifying the network by feeding it with a grayscale as input, thus reducing by one third the input dimensionality. Besides, the use of image subtraction used in the initial implementation could not capture some states; indeed, a better way to deal with changing environments over time is to feed the neural network a batch of images, them being the last N frames. This way, the state keeps track of past behaviors. By considering at least the last $N=2$ frames, velocity features can be extracted by the neural network from the image state.
307 |
308 | \begin{figure}[h!]
309 | \label{fig:ExampleExtractScreen}
310 | \centering
311 | \includegraphics[width=10cm]{images/example_extracted_screen.png}
312 | \caption[Pre-processed image of the environment]{Extracted screen from the inverted pendulum environment: the image is extracted by cropping, downsampling and applying grayscaling}
313 | \end{figure}
314 |
315 | \paragraph{Early Stopping}
316 | Thus, another method we can use is that of the \textit{Early Stopping}: in order to prevent overfitting, the agent is trained up to a point in which it has learned optimal behavior; from that point onward it would start behaving worse and worse and then restarting learning from scratch. We can detect this optimal situation by inserting a score threshold: when the mean of the last $K$ episodes overcome this threshold $\xi$, we stop the neural networks optimization. We have empirically set these two new hyper-parameters, which can be tweaked, to $K = 20$ and $\xi= 142$.\\
317 |
318 | \paragraph{Reward Function Design}
319 | The reward function design is one of the most important aspects in Reinforcement Learning and can make the difference between an agent not training at all and one able to achieve super-human performance. Instead of the usual reward function from OpenAI Gym, we can build a new one being able to better give a feedback on our agent's decisions:
320 |
321 | \begin{equation}
322 | \label{eq:reward}
323 | \begin{aligned}
324 | r_1 = \frac{x_{max} - |x|}{x_{max}} - 0.8 \\
325 | r_2 = \frac{\theta_{max} - |\theta|}{\theta_{max}} - 0.5 \\
326 | r_{tot} = r_1 + r_2
327 | \end{aligned}
328 | \end{equation}
329 | However, in this case the reward function just has a minor impact on the overall performance, so we may as well use one which doesn't explicitly employ the state variables.
330 |
331 | \section{Final Model}
332 | \begin{table}[h!]
333 | \centering
334 | \begin{tabular}{ |p{4cm}|p{3cm}|p{2cm}|p{1.5cm}|p{1.2cm}| }
335 | \hline
336 | \multicolumn{5}{|c|}{Parameters} \\
337 | \hline
338 | Layer & Number of Filters/Neurons & Activation & Kernel Size & Stride \\
339 | \hline
340 | Convolutional Layer 1 & 64 & ReLu & 5 & 2\\
341 | \hline
342 | Convolutional Layer 2 & 64 & ReLu & 5 & 2 \\
343 | \hline
344 | Convolutional Layer 3 & 32 & ReLu & 5 & 2 \\
345 | \hline
346 | Linear Output Layer & 1792 & None & - & - \\
347 | \hline
348 | \end{tabular}
349 | \label{table:NeuralNetwork}
350 | \caption{Convolutional Neural Network hyper-parameters}
351 | \end{table}
352 |
353 | After improving the model with the aforementioned techniques, we obtain the following Convolutional Neural Network described in Table \ref{table:NeuralNetwork}. As regards the loss function and optimizer, we use:
354 | \begin{itemize}
355 | \item Loss Function: \textit{Huber loss function}, which is:
356 | \begin{equation}
357 | L(Q_{target}, Q_{predicted}) = \frac{1}{2}(Q_{target}-Q_{predicted})^2
358 | \end{equation}
359 | \item Optimizer: \textit{RMSprop}, which is able to do a gradient descent of the error in almost the most optimal path
360 | \end{itemize}
361 |
362 | The Python code for the DQN is the following; it takes a sequence of images as input and outputs the value function corresponding to each action:
363 | \begin{minted}{python}
364 | class DQN(nn.Module):
365 | """Convolutional Neural Network predicting the state-action values"""
366 | def __init__(self, h, w, outputs):
367 | super(DQN, self).__init__()
368 | self.conv1 = nn.Conv2d(nn_inputs, HIDDEN_LAYER_1,
369 | kernel_size=KERNEL_SIZE, stride=STRIDE)
370 | self.bn1 = nn.BatchNorm2d(HIDDEN_LAYER_1)
371 | self.conv2 = nn.Conv2d(HIDDEN_LAYER_1, HIDDEN_LAYER_2,
372 | kernel_size=KERNEL_SIZE, stride=STRIDE)
373 | self.bn2 = nn.BatchNorm2d(HIDDEN_LAYER_2)
374 | self.conv3 = nn.Conv2d(HIDDEN_LAYER_2, HIDDEN_LAYER_3,
375 | kernel_size=KERNEL_SIZE, stride=STRIDE)
376 | self.bn3 = nn.BatchNorm2d(HIDDEN_LAYER_3)
377 |
378 | # Number of Linear input connections depends on output of conv2d layers
379 | # and therefore the input image size, so compute it.
380 | def conv2d_size_out(size, kernel_size = KERNEL_SIZE, stride = STRIDE):
381 | return (size - (kernel_size - 1) - 1) // stride + 1
382 |
383 | convw = conv2d_size_out(conv2d_size_out(conv2d_size_out(w)))
384 | convh = conv2d_size_out(conv2d_size_out(conv2d_size_out(h)))
385 | linear_input_size = convw * convh * 32
386 | nn.Dropout() # Adds further regularization
387 | self.head = nn.Linear(linear_input_size, outputs)
388 |
389 | def forward(self, x):
390 | """Forward pass in the network"""
391 | x = F.relu(self.bn1(self.conv1(x)))
392 | x = F.relu(self.bn2(self.conv2(x)))
393 | x = F.relu(self.bn3(self.conv3(x)))
394 | return self.head(x.view(x.size(0), -1))
395 | \end{minted}
396 |
397 |
398 | \begin{figure}
399 | \centering
400 | \includegraphics[width=\linewidth]{architecture.png}
401 | \caption{Architecture of the DQN with a Convolutional Neural Network for approximating state-action values}
402 | \label{fig:architecture}
403 | \end{figure}
404 |
405 | The final architecture of the DQN is represented in \ref{fig:architecture}. The following table shows the main Hyper-Parameters, based on the DQN with Experience Replay and Target Network, which further improves the performance of the system:
406 |
407 | \begin{table}[h!]
408 | \centering
409 | \begin{tabular}{ |p{6cm}|p{6cm}| }
410 | \hline
411 | \multicolumn{2}{|c|}{Hyper-Parameters Values} \\
412 | \hline
413 | Batch Size & 128 \\
414 | \hline
415 | Batch of Frames Size & 2 \\
416 | \hline
417 | Discount Rate $\gamma$ & 0.999 \\
418 | \hline
419 | Initial $\varepsilon$ & 0.9 \\
420 | \hline
421 | Final $\varepsilon$ & 0.01 \\
422 | \hline
423 | $\varepsilon$-Decay & 5000 \\
424 | \hline
425 | Early Stop $\xi$ & 142 \\
426 | \hline
427 | Image Height (pixels) & 60 \\
428 | \hline
429 | Image Width (pixels) & 135 \\
430 | \hline
431 | Maximum Memory Size & 100000 \\
432 | \hline
433 | Target Model Update $\tau$ & 50 \\
434 | \hline
435 |
436 | \end{tabular}
437 | \label{table:hyperParameters}
438 | \caption{Reinforcement Learning hyper-parameters}
439 | \end{table}
440 |
441 |
442 | \subsection{Final Results}
443 |
444 | After several unsuccessful or partially successful tries, using a tweaked CNN architecture, regulated hyper-parameters and adjustments in image pre-processing, dealing with overfitting and reward function design, we finally come to the experimental results.
445 | \medskip
446 | \begin{figure}
447 | \centering
448 | \includegraphics[width=\linewidth]{plot_score.png}
449 | \caption{Final results: plot of the obtained averaged out of a pool of 6 training runs. The light blue lines represent the confidence interval obtained via mean $\pm$ standard deviation. Most of the runs are able to get to the desired score in $\sim$ 800 episodes}
450 | \label{fig:results}
451 | \end{figure}
452 | As shown in Figure \ref{fig:results}, the inverted pendulum system is able to stabilize to obtain the 200 score. As to the best of the author's knowledge, this result has not been obtained yet in the Cartpole-v0 environment with DQN and only raw visual input, mainly because of the absence of early stopping which prevents overfitting.\\
453 |
454 | % \footnote{The algorithm can be found at this \href{https://github.com/fedebberto/Vision_Based_CartPole_DQN}{Federico Berto's Github repository}.}
455 |
456 | \section{Potential Improvements and Future Work}
457 | Reinforcement Learning is fast-paced research area and it is even difficult at times to catch up with the latest trends. Regarding the control systems in particular, algorithms such as the LQR and MPCs still offer better performance and, most of all, theoretical guarantees on stability, at the cost of needing more information on the state and/or model of the system. \\
458 | As we can also notice from the results, even though there is a confidence baseline for the stabilization score, the system is still prone to disturbances and inherent instabilities of the control policy and the neural network approximating the state-action values. One research direction would be to look for robust formulations of the problem \cite{DBLP:journals/corr/PintoDSG17}. Another interesting area, which has more technical guarantees on convergence and more efficient sampling of the state-space is the \textit{Model-Based} Reinforcement Learning \cite{DBLP:journals/corr/abs-1903-00374}, although it inherently needs a description via a model, thus renouncing the \textit{model-free} paradigm. Perhaps, the most interesting research direction is the combination of Reinforcement Learning and/or Optimal Control with Neural Ordinary Differential Equations \cite{NEURIPS2018_69386f6b}, a new class of Neural Networks which, thanks to their inherent capability to deal with differential equations, are revolutionizing the area of approximation and optimization of complex dynamical systems.
459 |
460 | \section{Conclusion}
461 | The goal of this report was to find a controller in a situation where state variables were not available, in particular by using only raw images to generate a control policy.
462 | The test benchmark we used is the inverted pendulum, which is used frequently to test non-linear controllers, which we used by extracting the necessary state information automatically thanks to the Deep Q-Learning, a Deep Reinforcement Learning algorithm capable of controlling agents with complex state-action spaces.\\
463 | After implementing several tweaks to existing algorithms, we were able to obtain a controller capable of successfully obtaining the maximum reward score in the simulation by using Convolutional Neural Networks for choosing the optimal action leading to the optimal cumulative reward. The successful stabilization of the inverted pendulum shows that Reinforcement Learning is indeed capable of achieving good performances even with diffucult tasks.\\
464 | Possible future developments include the implementation of new frameworks, such as Neural Ordinary Differential Equations, possibly paving the way to a better synergy of Reinforcement Learning and Optimal Control.
465 | \printbibliography
466 | \end{document}
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------