本日(2021-10-17)北海道北部で、今季初の積雪が観測されたとのことです。さっそく、北海道最北端の名山、利尻山(利尻岳)の様子をライブカメラで確認してみました。冠雪というよりも、かなりたくさんの積雪がみられました。これから長い厳冬になります。
![]() |
| http://www.town.rishiri.hokkaido.jp/rishiri/ ライブカメラから引用(15:00ころ) |
I am a professor emeritus of CS at Kanagawa Institute of Technology, Japan. Originally my specialty was parallel and distributed systems. My current interests include machine learning, natural language processing, creating mobile apps with MIT App Inventor, and quantum computing. In the web version of this blog, clicking the icon on the right (a plastic sphere) will take you to the "List of Quantum Computing Articles". - Fujio Yamamoto (for e-mail, add "@ieee.org" after "yamamotof")
【what is this】分類問題等で保持しているデータを使って機械学習させ、その結果を利用して、未知のデータを予測(分類など)したい場合があります。最近では、Tensorflow/Kerasなどを使えば、それは比較的楽に実現できます。ここでは、学習結果をスマホアプリに組み込み、スマホで利用することを行いました。Javascriptから使えるTensorflowJSやML5JSを利用しました。
■ 例題:1700万種の彩色を9種に分類するJapanese summary 本シリーズのPart1とPart2では、スマホ向けのQ-Learningアプリを開発し、それを簡単な例(直線の廊下でロボットが宝石を得る)に適用しました。今回は、このアプリを改訂し、2次元グリッドでロボットが行動できるようにしました。そして、グリッドサイズが大きくなるにしたがい、これまでのQ-tableを保持してQ値を更新する方法は、メモリ量と処理量の急増により破綻することを確認しました。それに変わる有望な方法として、Neural Networkの利用を検討し、それを(スマホではなく)PC上のPythonで実現した結果を示します。
Abstract
In Part 1 and Part 2 of this series, I developed a Q-Learning app for smartphones and applied it to a simple example (a robot gets a gem in a straight corridor). This time, I revised this app so that the robot can act on the 2D grid. However, as the grid size increases, the traditional method of holding the Q-table and updating the Q value becomes difficult due to the increase in memory capacity and processing volume. As a promising alternative, I considered using a neural network. And here's the result of doing that with Python on a PC (not a smartphone).
● Revised version of the Q-Learning app
In the revised version of the smartphone app, as shown in Fig. 1(a), the robot is trained to reach the gem while avoiding barriers on the 4x4 grid. The Q-Learning algorithm is basically the same as last time. There is one gem and one barrier, and their positions change randomly for each play (every episode). The robot also starts from a random position. After sufficient training, the robot can always reach the gem in the shortest route. On the other hand, if not well trained, the robot often gets lost and hits a wall, as shown in Fig. 1 (b).
● Memory capacity required for Q-Learning
The size of the Q-table required for this learning can be calculated according to the grid size and the number of gems and barriers. See Fig.2. The number of Q-table entries (i.e., the number of keys) is the total number of possible states, which in Case 1 (4x4) is 3,360. At this level, it can be held sufficiently even on a smartphone, and the amount of calculation is within an acceptable range. However, in Case2 (5x5), the total number of states increases sharply to over 6,000,000, even though only one gem and one barrier have been added. In this situation, regardless of whether it is a smartphone or a PC, processing is almost impossible due to both the amount of memory and the amount of calculation.
● Calculate Q-values with neural network (without holding Q-table)
For cases like Case2 above, you can think of a way to calculate the required Q-value with a neural network without holding the Q-table. To do this, transform the Q-value update formula for the neural network, as shown in Fig.3. This makes it possible to compare output and target ([1]). It can be used to solve this problem with common supervised machine learning. This machine learning iteration allows the output to be closer to the target and, as a result, the Q-value to be closer to the exact value.
Fig.4 clearly shows how to use this neural network in the case of Case1. Note that in this example, the action "W (west)" is taken in the current state S. In this way, one learning is done only for one action in one state. This learning should be repeated for as many actions as possible, in as many states as possible.
● Calculation example of Q-value by neural network
I implemented a learning method using such a neural network in Python and executed it on a PC. This program is based on the Python program (using Tensorflow / Keras) published by Dr. Makoto Ito in reference [1]. Fig.5 shows the learning process for Case1 (4x4). It shows the situation where 10000 episodes were randomly trained. In the upper graph, the average sum of rewards per episode has reached about 0.8. On the other hand, when the neural network is not used, as shown in the figure on the right of Fig. 1(a) (although the characters are small and difficult to see), it is 0.8305, so both results are almost the same. The lower graph shows that the average number of steps a robot takes to reach the gem is about 2.9. This value is also valid considering the situation in Fig.1.
Acknowledgments
I was able to create a Q-value calculation program using a neural network by referring to the Python program published in the reference [1]. I would like to thank Dr. Makoto Ito, the author of this article.
References
[1] Makoto Ito's Blog Article: M-note Program and Electronic Work (in Japanese)
http://itoshi.main.jp/tech/
Japanese summary 前回の記事では、スマホ向けのQ-Learningアプリを開発し、それを簡単な例(ロボットが宝石を得る)に適用しました。今回は、ロボットの行動にいくつかのバリエーションを与えてみました。その場合でも、新しい行動の記述を追加する以外は、このスマホアプリをほとんど変更していません。今回の例題でも、Q-Learningによる学習の結果、ロボットは宝石を得るための最適な手順を自ら発見できました。
Abstract
In the previous article, I developed a Q-Learning app for smartphones and applied it to a simple example (a robot gets a gem). This time, I gave some variations to the behavior of the robot. Even so, I haven't changed much of this smartphone app, except to add a new behavioral description. In this example as well, as a result of learning by Q-Learning, the robot was able to discover the optimal procedure for obtaining the gem.
# For the case where the robot moves on the 2D grid, please see this revised version.
● New examples (two cases)
As in the last time, as shown in the figure below, the task is for the robot to move the corridor and get the gem. The actions that the robot can take are different from the last time, but learning the best steps to successfully acquire a gem is the same.
● Learning results in Case1 and the robot moving example
As a result of fully executing Q-Learning for Case1, we obtained a highly accurate Q-table. Using it, the robot was able to discover the optimal procedure for obtaining the gem, as shown in Fig.1. In the initial state of this example, the positions of R (Robot) and G (Gem) are expressed as "R . . G . .". The corresponding maximum value of Q-table is given by "Forward" and "Jump" (where, both values are 3.0.). Whichever is adopted, it will be the same after all, but here, "Jump" was taken. At the transition destinations after this, the action that maximizes the Q-table value was also taken, so the gem was successfully acquired. This is the best procedure.
This app won the "2021 October's MIT APP INVENTOR OF THE MONTH" award.
Abstract
This app explains the basic idea and mechanism of reinforcement learning (especially Q-Learning), which is a field of artificial intelligence technology, using simple examples. Reinforcement learning is used in AlphaGo, autonomous driving, autonomous control robots, etc., and is attracting a lot of attention. Here, you can get familiar with the essence of the technology using your familiar smartphone before confronting such a practical level. As an example, a robot is trained to go straight down the corridor and successfully acquire the gem placed along the way. For this purpose, I use the reinforcement learning method called Q-Learning. Results of the training can be confirmed by the animation of the robot movement. I have developed a smartphone app that realizes these using MIT App Inventor. Q-Learning runs on your palm!
# This application for Android is published below:
Source code: here
# This app can also be applied to robots with more complex behaviors than the examples below. In that case, it is enough to add a definition of new actions and rewards. For details, please see Part 2 here.
# For the case where the robot moves on the 2D grid, please see Part3 here.
● Overview of the Q-Learning app
The configuration of the developed application is explained in Fig. 1. You can see a robot and a green gem in the corridor at the bottom. Train the robot to pick up the gem at the right place. (The robot's behavior will be explained later.) To do that, first press the "init" button, then train with the "train" button. Each "train" will learn 100 steps. One step corresponds to the robot moving one block in the corridor or picking up (taking) the gem.
At each step, the action is rewarded. Positive actions that lead to success are highly rewarded. A series of actions of the robot starting from the left end to the final success or failure is called an episode. Although the position of the gem changes with each play (game), the average rewards sum for successful episodes can be calculated theoretically in this example. Repeat "train" until it approaches this theoretical value. If the theoretical value cannot be calculated, the iteration should be stopped when it is considered to have converged to a certain high value.
The data in the large yellow area (Q-table) on the screen indicates which action is preferable (worth it) depending on the situation along the way. As I will explain later, with repeated training, this Q-table will approach the correct values.
After training, press the "anim for test" button to watch the robot's behavior in animation. A major feature of this reinforcement learning is that the behavior of the robot can be determined by the contents of the Q-table. Therefore, if the Q-table is inaccurate, it often fails as follows:
On the other hand, if the contents of the Q-table are correct, gem acquisition will always succeed, as shown below:
● Challenges imposed on robots and possible actions
Let's take this example in a little more detail. The actions that the robot can take, the conditions for obtaining the gem, and the conditions for completing the task (play) are shown in Fig. 2. On the other hand, Figure 3 illustrates whether “Take” (the action of picking the gem) or “Forward” (moving to the right) leads to success in a certain situation. To get the gem, the robot must do a "Take" action at the same place as the gem. Obviously, in this example, the robot should select (2) "Forward" instead of selecting "Take" in (1). After that, select "Take" in (3) and it will succeed.
● How to choose an action
As already mentioned above, I introduced rewards to determine whether to choose between “Take” action and “Forward” action in a particular situation. As shown in Figure 4, the reward is +5 for the "Take" action that succeeds in acquiring the gem, and -1 for the other actions. And it is advantageous to choose an action with a larger sum of rewards mentioned above.
● Update Q-table
To achieve the above, I use a Q-table that represents the value (in other words, worth) of both actions for the state at that time, as shown in Figure 5. In the figure, in the untrained state (train = 0 step), the action value of "Take" is higher (larger) than that of "Forward", so the "Take" action is selected. But this is wrong because the Q-table is inaccurate. On the other hand, in the fully trained state (train = 800 steps), the Q-table has been updated to a reasonable value, and the "Forward" action is taken correctly. Roughly speaking, Q-table is an estimate of the sum of rewards.
The Q-table update is based on a famous learning rule called Q-Learning as shown below:
● Even deeper expansion
The above example is to familiarize you with the basic idea of "Q-Learning". In this example, the number of states is so small that the entire contents of the Q-table could be saved and updated. However, consider an example where the robot's range of movement is not a one-dimensional corridor, but a wide plane, or there are places where it cannot proceed due to obstacles. In such cases, the number of states will be enormous and will not be solved by basic Q-Learning. Therefore, the Q-table needs to be approximated by another method. One promising method is to use neural networks. The training itself will need to be done on a PC, but it will be possible to bring the trained model to a smartphone and run the animation for testing. I would like to discuss such advanced expansions in another article.
Acknowledgments
This app is my original work. However, I refer to the explanation of Q-Learning and the example Python program in reference [6]. I would like to thank Dr. Makoto Ito, the author of this article.
References
[1] Richard S. Sutton and Andrew G. Barto, "Reinforcement Learning: An Introduction, second edition", The MIT Press, 2018.
[2] Vincent François-Lavet, Peter Henderson, Riashat Islam, Marc G. Bellemare, Joelle Pineau, "An Introduction to Deep Reinforcement Learning", Now Publishers, 2019.
[3] Etsuji Nakai, "Reinforcement Learning for Software Engineers", Gijyutsu-Hyoron-Sha, 2020. (in Japanese)
[4] Azuma Ohuchi, Masahito Yamamoto, Hidenori Kawamura, "Theory and application of multi-agent systems - computing paradigm for complex systems engineering", Corona-sha, 2002. (in Japanese)
[5] Tomah Sogabe, "Introduction to reinforcement learning algorithm", Ohmsha, 2019. (in Japanese)
[6] Makoto Ito, “Learn Reinforcement Learning with Python”, Nikkei Software 2021.07, Nikkei BP, 2021, pp.24-39 (in Japanese)
[7] Kate Manning and Emily Kager,
https://github.com/MillsCS215AppInventorProj/chartmaker
【what is this】最近の日経ソフトウェア誌に、「Pythonで強化学習を学ぶ」の解説記事がありました。丁寧に書かれていて分かりやすく、提供されているPythonプログラムも完全に動かすことができました。しかし、ここで留まらずに、理解をさらに深めるため、別のプラットフォーム(Androidスマホ)とプログラミング環境(MIT App Inventor)で、独自にそれを再構築してみました。
■ 解説記事:Pythonで「強化学習」を学ぶすでに募集は締め切られていますが、生徒・学生のためのIT関連コンテストがありますので、ご紹介します。以下の2つは、いずれも小生が応援しているものです。
●U18 IT夢コンテスト(神奈川工科大学主催)
●MIT App Inventor Summer Appathon(米国MIT主催)
(2)MIT App Inventor Summer Appathon(米国MIT主催)
こちらは、3つのテーマ(City of the Future, Improving Academics, Community Computational Action)に関するアイディア(説明書とビデオも必須)とそれを実現したスマホアプリの提出が必要です。提出はすでに締め切られています。現在、誰でも投票できる「People's Choice Award」を受け付けています。彼らがどんなアイディアを持ち、どうそれを実現しているかを知って、応援しましょう!(今後、審査員による賞の発表もあります。)
https://appathon.appinventor.mit.edu/
【what is this】前回の「Scratchで強化学習(2)」の続編です。伊藤真著[1]にある、レベル3の例題を検討します。前回のレベル2では、開始状態から最終状態までの「エピソード」を扱いましたが、今回の例題は最終状態の無いゲームでの得点(報酬)を競うものです。予測報酬(=行動価値Q)の計算において、「割引率」を導入するのがひとつのポイントです。
■ レベル3例題:お化けの飛行訓練ゲームSometimes I write old, nostalgic articles. The following is what happened when I went to the United States in July 2014, seven years ago, to present my paper at the MIT App Inventor Summit 2014.
Perhaps modern students have never heard or touched what is called a "slide rule", but it was widely used in the world of technical computing. For example, it was actually used in some US national projects, so it's no wonder that some traces of it remain in the United States. The picture below is the elevator entrance of a hotel near MIT (Massachusetts Institute of Technology) where I was staying. I was surprised that a huge slide rule was hung on the top of the elevator door.
![]() |
| A huge slide rule at the entrance of the elevator |
![]() |
| Enlarged view |
The slide rule was discontinued 40 years ago with the advent of electronic calculators, but I still hold one of them. It was probably produced over 50 years ago. The photo below shows the calculation of "2 x Pi = 6.28" using this slide rule. In addition to multiplication and division, the slide rule can also be used to calculate trigonometric functions, logarithms, square roots, cube roots, etc. by exchanging the middle pard rule.
![]() |
| "2 x Pi = 6.28" on my slide rule |
Most of the slide rules made in Japan, including the one shown in the above figure, were made of bamboo. Therefore, there is little deterioration in accuracy due to temperature and humidity fluctuations, and it has been highly evaluated worldwide. The times have advanced. And in the new era, the physical slide rule has disappeared, but as you can see in the picture below, there is a "slide rule software" for Android smartphones! It is useful for understanding the principle of a slide rule.
![]() |
| "2 x Pi = 6.28" in the slide rule app |
【what is this】前回の「Scratchで強化学習」の続編です。伊藤真著[1]にある、レベル2の例題を検討します。前回のレベル1では、「行動、報酬」だけでしたが、今回は「状態、行動、報酬」を扱う本格的な強化学習の仕組みが入っています。そこにおいて、各状態での行動に対する予測報酬(=行動価値Q)の計算を観察します。
[->続編はこちら]