ラベル reinforcement learning の投稿を表示しています。 すべての投稿を表示
ラベル reinforcement learning の投稿を表示しています。 すべての投稿を表示

2021年11月5日金曜日

スマホでニューラルネットワーク(ml5JS/TensorflowJS利用)その2

【what is this】引き続き、「スマホでニューラルネットワーク」にこだわります。以前の記事 [1]では、Q-Learning(強化学習)をニューラルネットワークで行うための基本手法を検討し、実装しました。今回は、さらにそれを深めた手法である「Experience Replay + Target Networks」があることを知り、それをTensorflow.js (JavaScript環境)で構築し、妥当なQ値が得られるまでPCで学習させました。さらに、その学習済みモデルをスマホへ格納し、スマホのアプリとして、Q-Learningを用いた2Dグリッドの経路探索課題を解きました。

■ ExperienceReplay+TargetNetworksによるQ-Learningスマホアプリ
 この手法によるQ-Learningの結果を先に示します。課題は参考文献[1]で扱ってきた、2Dグリッドでの経路探索です。Fig.3にあるように、ロボットが壁や障害物を避けて宝石(緑色の球体)に最短距離で到達するように学習させます。その学習結果を、スマホアプリで示したのがFig.3です。この例では、ロボットが障害物(黒色の正方形)を避けてうまく宝石に到達するルートを学習したことが分かります。

■ ExperienceReplay+TargetNetworksの概要
 
強化学習は一般に、「教師付き学習ではない」と言われています。強化学習では、固定した正確なラベル(目標)を設定すること自体が困難です(というよりも、それ自体が求める解なのですから)。しかし、刻々変化するラベルを対象として、ニューラルネットワークで「教師付き学習」させる方式があります。それが、文献[1]で検討したものです。

 しかし、この方法には、2つほど欠点があります。一つは、「ある状態に対してある行動を取った場合」の一組づつしか学習できない。つまり、ニューラルネットワークで本来の性能を発揮するためのミニバッチ処理(多数の入力の一括処理)ができないことです。第二は、もっと本質的な問題ですが、この方法では、「状態と行動」が強く結合した学習となってしまい、多様な入力(状態)に対する学習が収束しずらいか、振動してしまう可能性が高いことです。

 これを解決すべく登場したのが、今回の「Experience Replay + Target Networks」なのです。小生の場合、参考文献[2][3]を読んでその概要を学びました。Fig.1に示すPseudo codingは文献[2]から引用したものです。これに従って、独自にJavaScript(Tensorflow.js使用)でそれを試作することができました。


 大雑把に言うならば、上図において、ExperienceReplayは、ミニバッチによる教師付き学習を可能にするために、replay memory Dに「状態と行動に関する観測結果」を蓄積していきます。そして、TargetNetworksの方は、上に述べた「状態と行動の関連性」を解消すべく、学習用のニューラルネットワークとは別に用意された、予測(prediction)用のニューラルネットワークです。すなわち、2つの分離されたネットワークを使います。TargetNetworksは、定期的に、学習用のネットワークの重みで置き換えられて、新しくなって行きます。このため、学習と予測のネットワークに時間差が生じますが、これが実は求めるべきQ値の推定を安定させることに繋がる。そのように考えられます。

■ Tensorflow(Python)よりもTensorflow.js(JavaScript)を使った理由
 この手法の実装における、「出力値とラベルの差(誤差)」の最小化を図るには、やはりTensorflowの学習関数(fit)を使うのが便利です。Pythonでやってももちろん良いのですが、今回は、JavaScript上のTensorflow.jsを使いました。その理由は、スマホアプリとの相性が良いことによります。
 ただし、学習済みモデルは、スマホ(あるいは外部の)webサーバに配置する必要があります。スマホ用のwebサーバーはいくつも公開されていますので、手軽に使えます。Fig.2はその一例です。この例では、学習済みモデルは2つのファイル(ネットワークトポロジー等の.jsonと重みの.bin)が、スマホのwebサーバに配置されています。スマホのアプリ側では、このモデルを(JavaScriptプログラムで)ロードして、予測に使うことができます。


■ 留意点:ExperienceReplay+TargetNetworksをTensorflow.jsで行う場合
(1)Tensorflow.jsは非同期関数
 Tensorflow.jsは非同期関数の仕様になっているので、その使用は、非同期関数(先頭にasync付き)の中で行う必要があります。そして、学習用のfit関数等を呼び出す場合は、awaitによって、fit関数の実行終了を待つ必要があります。そうしないと、思わぬところで別のコード部が実行されたりしますので、注意が必要です。

(2)モデルのsaveとloadの方法
 上に述べたように、学習用のネットワークtrain_netの重みを、定期的にTatget Networksへloadする必要があります。その際に、Tensorflow.jsは、非常に使いやすいsave/loadの仕組みを提供しています。つまり、以下のように、ブラウザのメモリにsaveできる、localstorageスキームを使うことができます。
    // target_netのモデルを更新するため、train_netのモデルをsave
    await train_net.save('localstorage://2dgrid_model');
    // train_netのmodelをtarget_netへロード
    target_net = await tf.loadLayersModel('localstorage://2dgrid_model');

 一方、これとは別に、train_netの学習済みモデルを外部へ取り出して利用したい場合には、downloadsスキームによって、save/loadを行うことができます。以下はその例です。
    // 学習済みモデルのダウンロード
    await train_net.save('downloads://2dgrid_model');
    // 学習済みモデルをmodelフォルダに配置してそこからload
    train_net = await tf.loadLayersModel('./model/2dgrid_model.json');

  なお、loadした学習モデルを単に予測に使うだけなら、これOKですが、さらにそれを学習させる場合は、以下のように、再度、最適化関数を同じものに設定してコンパイルする必要があります。
    train_net.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

(3)学習関数fitへ与える入力データの形式
 PythonでのTensorflowでは、fit関数の引数となる訓練データとラベルデータは、pandas array形式ですが、Tensorflow.jsでは、通常配列をtensor2dで変換して与えます。

【注】上記の(1), (2)は、Tensorflow for JavaScriptの下位レベルAPIであるCore APIを使った場合です。そうではなく、上位レベルAPIであるLayers APIを使う場合には、非同期性を考慮しなくても使える関数が用意されています。

■ ニューラルネットワークの構成と学習性能
 上に述べた2つのニューラルネットワーク(学習用と予測用)の構成は以下のようにしました。試行錯誤の結果、これに落ち着きました。隠れ層は1層よりも2層の方が良い。また、隠れ層1層目のノード数はやや多い方が良い(ここでは128とした)などが分かりました。活性化関数は、隠れ層ではreluに、出力層ではlinearに設定しました。
_______________________________________________________
Layer (type)                 Output shape              Param #   
=================================================
dense_Dense1 (Dense)     relu    [null, 128]                512       
_______________________________________________________
dense_Dense2 (Dense)     relu    [null, 32]                 4128      
_______________________________________________________
dense_Dense3 (Dense)     linear  [null, 4]                  132       
================================================
Total params: 4772
Trainable params: 4772
Non-trainable params: 0
_______________________________________________________
(各隠れ層の後にdropout層を挿入した場合も試しましたが、この問題に関しては、特段の効果は確認できませんでした。)

 Fig.3に示した4x4グリッドについて、学習したモデルを次回の学習の初期モデルにしてさらに訓練を続けるというやり方で(ε-Greedyのεの値はその度に一定比率で減少させて)学習させました。その結果を使って、状態(宝石の位置、障害物の位置、ロボットの位置)をランダムに100組み生成して、ロボットが宝石に最短距離で到達できるか否かをテストしました。その成功率は以下の通りでした。
・1回目:0.97
・2回目:0.95
・3回目:0.97

■ 感想
 「不正確なラベル」を使って「近似的な解法」を実行して行くという、この(一見確信を持てないような)手法ですが、実際にやってみると段々にラベルが正確な値に近づき、正しい答えを出すようになるのは不思議な気もします..
 この手法で学習させた結果は、上記のとおり、かなり満足のできるものでした。従来のベルマン方程式に基づくQ-tableを構築しながら学習させる方法では、ほぼ確実に厳密解に到達できました。これに対して、今回のニューラルネットワークを用いた上記のExperience Replay + Target Networksでも、95%程度の正解率を得ることができました。そして、問題規模がさらに増大した場合は、Q-tableによる学習は明らかに破綻するので、今回の手法の有効性が高まるものと感じます。

 この実装は、ほとんどFig.1の情報だけから出発して(参考文献[2]や[3]に載っていたPytonコードを見ずに)、自分で考えながら具体化し、Tensorflow.jsを使って実現しました。どこか間違っているかも知れないという不安は残っていたのですが、上記のとおり95%の正解率を得ることができたので、恐らく、妥当な作りになっているだろうと思います。

参考文献
[1] Running Q-Learning on your palm (Part3)
[2] Jordi TORRES.AI, Deep Q-Network (DQN)-II
Experience Replay and Target Networks, Aug.16, 2020

[3] Ketan Doshi, Reinforcement Learning Explained Visually (Part 5): Deep Q Networks, step-by-step
A Gentle Guide to DQNs with Experience Replay, in Plain English, Dec 20, 2020


2021年9月25日土曜日

Running Q-Learning on your palm (Part3)

Japanese summary 本シリーズのPart1Part2では、スマホ向けの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.


I have omitted the details, but in the case of Case2 (5x5), I was able to train well with this neural network as well. It took only about 3 minutes to run on a general PC, so I was able to confirm the usefulness of this method. This time I've only used the most basic neural networks, but for more complex problems (for example, if you need to remember the location of an object), you may need other neural networks such as LSTMs.

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/

2021年9月12日日曜日

Running Q-Learning on your palm (Part2)

 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.



Consider the following two cases regarding robot behavior and its rewards. In both cases, an episode ends when a "Take" is performed (regardless of success or failure) or the robot deviates from the corridor boundary.

Case1:
  • Take: Take the gem (reward = +5 if successful, otherwise -1)
  • Forward: Move forward one block in the corridor (reward = -1)
  • Jump: Move forward two blocks in the corridor (reward = -1)
Case2:
  • Take: Take the gem (reward = +5 if successful, otherwise -1)
  • Back: Go back one block in the corridor (reward = -1)
  • Skip2: Skip two blocks in the corridor (reward = -1)

 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.


 Learning results in Case2 and the robot moving example
The robot's actions possible in Case2 is different from Case1, but similarly, the robot was able to discover a procedure for obtaining the gem. The situation is shown in Fig.2. In the initial state of this example, the positions of R (Robot) and G (Gem) are expressed as "R . G . . .".  This procedure is optimal by combining "Skip2" and "Back".


Here's another slightly more complicated example in Case2. See the Gif animation below. In this example, the robot found the best steps to get the gem:

“R . . . G .”  →Skip2BackBackSkip2Take[success]

 Setting rewards according to purpose
The reward values shown above can be changed depending on the purpose. For example, unlike the above, let's say you want to get the gem in the best way, even if the robot starts at any position. In such cases, change the reward design of Case 2 as follows and name it Case 3.

Case3:
  • Take: Take the gem (reward = +5 if successful, otherwise -1)
  • Back: Go back one block in the corridor (reward = -1 if it is in the corridor after moving, otherwise -2)
  • Skip2: Skip two blocks in the corridor (reward = -1 if it is in the corridor after moving, otherwise -2)

This reward design will serve your purpose, as in the examples below:


2021年8月26日木曜日

Running Q-Learning on your palm (Part1)

Japanese summary このアプリは、人工知能技術の一分野である「強化学習(特にQ-Learning)」の基本的な考え方と仕組みを、簡単な例を動かしながら学ぶものです。強化学習は、AlphaGo(囲碁)や自動運転、自律制御ロボットなどで使われ、注目を集めています。ここでは、そのような実用レベルに立ち向かう前に、身近なスマートフォンを用いて、その技術のエッセンスに触れて親しむことができます。あなたの掌の上のスマホで強化学習を楽しもう!(このアプリは、MIT App Inventorを用いて開発されました。)

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.




It is easy for humans to write a program to solve this problem (challenge). But here, instead, let the robot itself discover the solution through learning. Please note this point!

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:


This update formula means that the value of Q when taking an action in the current state is brought close to the highest value of Q that can be taken in the next state. It is known that such updates converge to the optimum Q value, assuming a sufficient number of episodes are attempted for all states. If you need a more detailed explanation, please see one of the references ([1][2][3][4][5]). And the relationship between this value of Q and the Q-table in this application is illustrated below:


In fact, the figure below shows that the contents of the Q-Table have almost reached optimal after 1100 steps of training.


Expand the app a little
Finally, here is an example of how to expand this app. This app has three hyper parameters (α, γ, ε) to increase versatility. For example, how much will the convergence speed and stability be affected if the value of the learning rate α is changed?

To confirm this, you need to display it as a line graph instead of the slider as above. It's easy to achieve. I used ChartMaker (an extension created by Kate & Emily) in reference [7]. The result is shown in Fig.6.

Enjoy reinforcement learning (Q-Learning) with this smartphone app! 

 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


2021年7月26日月曜日

Scratchプログラミングで強化学習の基礎(1)

【what is this】子供向けと言われるScratchですが、伊藤真著[1]にはゲームの形で、強化学習(3段階に分けたQ学習)が、実に丁寧に説明されています。大人にも有用と思われます。本記事では、このうちの最初の例題(レベル1)を対象として、(小生独自の改造も加えて)強化学習を詳しく観察します。
[->続編はこちら]

■ レベル1例題:砂漠でダイヤ集めゲーム
 レベル1例題は、図1(a)に示す左右の穴を掘って、ダイヤをたくさん集めよ、というものです。左右の穴はダイヤが出る確率が異なりますが、その確率はプレーヤーには知らされていません。ダイヤが出れば報酬1、出なければ報酬0が与えられます。プレーヤーは「人間」と「強化学習」です。限定された試行回数において、総報酬(=得点)をできるだけ多くするには、どのような戦略で左右の穴を選択すべきでしょうか?


 図1(a)はオリジナルのステージデザインですが、(b)は、後述する「予測報酬確率」の推移をグラフ化するための改造版です。

■ 「人間」プレイヤーの戦略
 人間がプレイヤーの場合、色々な戦略が考えられます。全くデタラメに左右を選ぶのではなく、ここでは、ひとつの方法として、以下の戦略をとります。例えば、試行回数100回の場合、
  1. 最初の25回は左を選択し続けて、その穴のダイヤ出現確率を予測。
  2. 次の25回は右を選択し続けて、その穴のダイヤ出現確率を予測。
  3. 残りの50回は、上記の確率の高い方の穴を選択し続ける。
 この方法は、前半の50回を「探索」に、後半の50回を「活用」に費やすものであり、これでもある程度高い得点が得られるでしょう。

■ 「強化学習」プレイヤーの戦略
 この強化学習の戦略は、試行の度に、左右のダイヤの出る確率(予測報酬確率)を更新し、その時点で確率が高い方の穴を選択します。ただし、ある小さな確率(乱雑度ε)で、それには従わずにデタラメに右が左を選びます。図2がその概要です。この書籍では明記されていませんが、このような枠組みは、一般にε-greedyポリシーと呼ばれるものです。


 上記の左右の予測報酬確率は、図3に示す学習則で更新されます。左右どちらかの穴が選択される毎に、その穴に対する予測報酬確率が更新されます。小さな値の学習率を使って、予測報酬が実際の報酬に徐々に接近することが期待されます。なお、1回当たりの報酬は、図2に示すとおり、1か0です。


■ 報酬確率が途中で変更になった場合、どちらが有利?
 両方の戦略を実際に数回(いずれも試行回数100回で)試してみました。「強化学習」の方がやや優勢のようでしたが、それほどの差はないようです。「人間」の戦略でも、両方の穴の報酬確率は、25回の試行である程度正確に掴めるからでしょう。ただし、ここには、前提条件があります。つまり、両方の穴の報酬確率はもちろん知らされていないのですが、その報酬確率は途中で変わらないという前提です。

 もしも、報酬確率が途中で変わるとどうなるでしょうか。前半で左右の穴の報酬確率を予測、後半でそれを活用、という「人間」の戦略では、後半で報酬確率が大きく変動した場合、悲惨な結果となるでしょう。

報酬確率が途中で変動しても対応できる「強化学習」
 このような、報酬確率が変動する場合でも、「強化学習」の方は対応できます。以下で、それを実際に確認します。図4(a)は、前半50回までの左右両穴の予測報酬確率の推移をグラフにしています。(実際の)報酬確率は左が0.7、右が0.4であり、予測報酬確率は、その付近を振動しています。そして、実際、左右の選択は、左が41回、右が9回であり、順当に進行しています。


 さて、ここで(51回目で)、左右の報酬確率が大きく変動しました。つまり、左右の報酬確率が入れ替わってしまいました。でもご心配なく。間もなく、予測報酬確率も、それに追随して減少(左の穴の場合)、増大(右の穴の場合)していることが分かります。右側の予測報酬確率の上昇により、右側の選択回数が上図の9回から38回まで増大しています。


 結論として、100回の試行において、上記の報酬確率(0.4〜0.7)のもとで、68点という良い得点が得られました。なるほど強化学習!という感じです。
(ただし、「途中で報酬確率が変わる」と言っても、変わった後の新しい報酬確率が一定期間持続するという前提においてです。全くデタラメに報酬確率が変化するのであれば、どんな戦略も有効とならないでしょう。)

■ 補足
 今回の例は、冒頭に述べたように、レベル1という初歩段階のものです。一般的な「強化学習」は、「状態、行動、報酬」を基に行われますが、今回は「状態」は扱わないものとなっています。レベル2,レベル3になると、「状態」も使った本格的な強化学習になって行きます。

■ 感想
 普段、PythonやJavaでプログラミングしている人にとっては、Scratchは別世界です。まどろっこしく感じる場面も多いです。しかし、本例のように、何かをもっと詳しく調査したい、その結果も素早くビジュアルにしたい、そういう場合はとても便利な開発環境だと感じました。そして、あまりプログラミングに馴れていない人に、説得力をもって説明する場合の助けになるとも思いました。

参考資料
[1] 伊藤 真:ScratchでAIを学ぼう- ゲームプログラミングで強化学習を体験、日経BP、2020年8月11日第1版

2021年7月10日土曜日

今いちど強化学習のCartPole(倒立振子)問題

【what is this】強化学習の定番例題のひとつに、CartPole(倒立振子)があります。多くの場合、ポールの初期状態をほぼ真上(北向き)にしていますが、完全に倒れた真下(南向き)にした場合でも、うまく学習できて、長時間ポールを立て続けることができます。

■ CartPole(倒立振子)問題 - 制御工学と強化学習
 この問題は、よく知られているように、台車にポールを立てた状態を長く維持するための制御です。図1にあるように、当初は制御工学の問題(1)だったと思います。それが、強化学習で著名なR. S. Suttonの書籍(2)で、Q-Learning(=強化学習の手法のひとつ)の例題としてとり上げられました。その後さらに、強化学習の実行とテスト(シュミレーションによる)のための例題として、MATLAB(3)や、OpenAI(4)で扱われています。

図1 CartPole(倒立振子)問題 - 制御工学と強化学習

■ Q-LearningでCartPoleを解く
 ここでは、OpenAIのGym(その中の"CartPole-V0"という環境)を使います。全体の状態は、台車の位置と速度、ポールの角度と角速度の4項で表現されます。これらは連続量なので、Q-Learningで扱うには、これらを離散化(連続量を6区分するなど)します。台車の制御は、単位時間毎に一定の力で右へ押すか、左へ押すかだけです。その動作に反応したポールの新しい状態は、Gymが運動方程式の計算結果として返してくれます。ただし、各時点でその状態がどの程度好ましいのかを示す点数付け(報酬付与)は、自分で設計します。

 ここでの問題は、どういう状態の時、台車をどちらに動かすのが良いかを学習させることです。それをQ-Learningという手法で実行します。OpenAIのGymを利用したのは、上記の力学計算をやってくれるとともに、台車とポールのアニメーションも提供されるからです。ビジュアライゼーションはいつも重要です!

■ Q-Learningによる学習結果をみる
 技術的詳細は置いておき、結果を楽しみましょう。以下の図は、まだ学習があまり進んでいない段階です。すぐに倒れてしまうことが多いです。アニメーションの途中で、ガクッとなっているのは、そこでポールが倒れることを意味しています。真北から左右に12度以上開いた角度になった時がそれに該当します。倒れるとその試行(エピソード)が終了し、直ちに、次の新しい試行に入っています。

学習初期の状態(開始時、ポールの向きはほぼ真上

 一方、次の図は、学習がかなり進んだ段階です。上図に比べると、だいぶ長い間、ポールが倒れずに台車を制御できていることが分かります。

学習終盤の状態(開始時、ポールの向きはほぼ真上

 さて、上記では、新しい試行はいつもポールをほぼ垂直に(僅かに左右に傾けて)立てた状態から開始しました。それでは、今度は、ポールが完全に倒れた状態、すなわち、真南を指している場合はどうでしょうか。その状態から、ポールを真北に向けてそれを維持するのはかなり大変そうに思います。
 これを、深層学習(DQN : Deep Q Network)を用いてQ-Learningでやった報告が参考資料[1]にありました。それを追試した結果が以下の図です。

学習終盤の状態(開始時、ポールの向きは真下

 うまく行っています!ポールが、真下から持ち上がっています。このDQNでは、Chainer(Tensorflowでも良いのですが)を使っています。中間層のノード数は150で、この状態になるまでに約1,000エピソードを学習させました。実行時間は、通常のPCで10分程度でした。
 このようなアニメーションで興味を抱き、強化学習の詳細に入って行くきっかけになればよいですね。

参考資料
[1] 制御工学の基礎あれこれ
http://arduinopid.web.fc2.com/index.html

2021年5月28日金曜日

レンタカーショップ問題(強化学習での行動ポリシー最適化)

    【what is this】強化学習における「状態価値関数」をとりあげてきましたが、今回もその続編です。理論と手法の詳細は参考文献[1]を熟読戴くことにして、ここでは、「レンタカーショップ問題」と呼ばれる複雑な問題がこれに基づいて解けることを楽しみたいと思います。

レンタカーショップ問題(Jack's Car Rental)
 この問題は著名なSuttonの著作[2]にありますが、簡潔に1ページに纏められており、そこから自分でプログラムを作るのは難しそうです。しかし、中井悦司著[2]では、実に丁寧にこの問題の設定と具体的な解法(Pythonプログラム付き)が解説されており、非常に有用です。このブログ記事は、それにしたがって学んだ結果を小生なりにまとめたものです。

 図1に、この問題の設定条件を示しました。2つの店Aと店Bを持つオーナーが、車貸出しによる利益を最大にするために取るべき行動(戦略)を求めます。その行動とは、営業終了後の夜間に、2つの店の間で適当な台数の車を移動させることです。両店の貸出し/返却の台数の発生確率が異なるため、翌日の営業に備えて、両店の車の台数を調整する必要があるのです。ただし、車を移動することで一定の損失(余分なガソリン代など)が発生します。


 両店の貸出し/返却の台数の発生確率は、ポアソン分布に従っており、その期待値は図1の説明文にあるように分かっているとします。図2に示すような確率分布となります。


マルコフ決定過程における確率的な状態遷移
 この問題を解くためのベースとなる状態遷移を図3のように定めます。ある時点の状態は、店Aと店Bに現在残っている車の台数のペアとします。営業終了時(午前中は貸出しのみ、午後は返却のみ)の状態をSとします。それに対するアクションa(行動a)は、夜間に店Aから店Bへ|a|台の車を移動させることを意味します。逆向きの移動ではaの値は負値になります。その行動が終わり、さらに翌日の営業が終了した時点の状態をS'とします。つまり、状態Sにアクションaを適用した結果の状態がS'です。

 状態S'では、車の移動による損失と、貸出しによる利益が確率から計算されています。貸し出し/返却台数は乱数で決まるので、図3の遷移は、確率的な状態遷移を含むマルコフ決定過程といえます。この状態遷移をもとに、先の記事でも述べたベルマン方程式を作ることができます。ベルマン方程式を解くことは、各状態の価値(状態価値関数)を計算することになります。

 そして、状態価値関数はアクションaによって決まるわけであり、どの状態に対しても最も大きな状態価値観数値を与えるアクションを求める方法があります。その一つが、ここで使われている価値反復法と呼ばれるものです。

価値反復法によるレンタカーショップ問題の最適解
 この方法は(詳細はここには書けませんが)、行動-状態価値関数計算とGreedyポリシーの更新と状態価値関数の更新をセットとして、全ての可能な状態(店Aと店Bに残っている台数のあらゆる組合せ)について行います。それを、すべての状態について変動がなくなるまで反復します。反復一回あたり計算量(可能なあらゆる台数についての確率計算を含む)は相当に大きくなりますが、種々の効率化手法がとられます。最終的には、比較的少ない反復回数(数十回程度)で収束解(最適解)が得られるようです。図4は、収束の途中の解(行動ポリシー)を示しています。


 そして、図5は、収束した最適解(最適行動ポリシー)の拡大図です。一つのマスは、一つの状態(店Aと店Bに残っている台数のペア)です。マスの中の数値は、店A→店Bへ|a|台の車を移動するという行動を意味します。この結果を眺めてみて、十分納得ができるように思います。

 全体としては、残っている台数が両店間で偏っている場合は、それを補正する方向になっています。ただし、両店の貸出し台数の期待値(ポアソン分布の)の違いを反映して、店Aから店Bへの移動が多くなっています。
 例えば、店Aに15台、店Bに2台残っている状態では、限度いっぱいの5台を店Bへ移動すべきとなっています。これは、店Bの方がポアソン分布の期待値が大きいことを反映しています。逆に、店Aに2台、店Bに15台残っている状態では、店Bの方が期待値は大きいものの、店Bから1台を店Aへ(少し損失は生ずるが)移動した方が全体の貸し出し数は増えるという判定となっています。


 図5の最適行動ポリシーによる状態価値関数の値を図6に示します。両店にともに車が多く残っている方が、翌日の営業での利益を大きく期待できることを示しており、これも納得できます。

感想
 冒頭に述べた中井悦司著[1]は、全体で5章の構成、本文全276頁です。今回の話題は、そのうちに第3章(全体の約6割)までの集大成と言えます。つまり、状態遷移を表す条件付き確率が全て計算できる「環境が分かっている」場合の基本的な強化学習理論の結論であると言えましょう。

[参考文献]
[1] 中井悦司:ITエンジニアのための強化学習理論入門、技術評論社、2020年7月
[2] Richard S. Sutton and Andrew G. Barto, "Reinforcement Learning : An Introduction", second edition, The MIT Press, 2018.

2019年10月11日金曜日

MATLABの強化学習Toolboxと自作Javaで簡単なGrid World探索

【要旨】MATLAB(R2019a以降)には、強化学習用のToolboxがある。それを使った簡単なGrid Worldの強化学習例題を試行した。同時に、自作Javaプログラムでも同じ例題を実行して理解を深めた。

 前回の強化学習の記事では、参考文献[1]に従って、行動価値関数を計算するためのQ学習を、Javaプログラムを自作して、3x3の簡単なグリッドに対して行いました。そのプログラムを、もう少し複雑な例題に適用してみたいと思っていました。それに最適な例題が、最近アナウンスされたMATLABのReinforcement Toolboxの解説に載っていました。それをやってみました。

 その例題の概要は図1のとおりです。詳細は、参考文献[2]をご参照下さい。5x5のグリッドワールドで、開始状態から終了状態までの、累積報酬が最大になる経路を学習させるものです。可能行動は、東西南北の4方向。障害物があり、また、special jump(ワープ)が設定されています。どの動きも次の状態で-1の報酬を得ます。罰としてです。例外は2つです。最終状態に達した場合は+10の報酬、また、特定の状態に到達した場合のみ、無条件に特定の状態にワープし報酬+5が動的に得られます。



これをQ学習で解くMATLABプログラムの主要部は図2のとおりです。Reinforcement Toolboxを使っているのが特徴です。詳細は、ここには書けませんが、これはPythonがMATLABになり、KerasがReinforcement Toolboxになったような感じです。


 これを学習(training)させた結果が図3です。結論として、赤丸の軌跡が最適経路であることを学習できました。そして、その経路で得られた累積報酬額は、+11です。これが可能な累積報酬の最大値であることは明らかです。


 今回の記事の本題は、実は、上に示した自作Javaプログラムでこの例題を解くことでした。結論を述べますと、自作プログラムでも同じ結果が得られて、ひと安心というところです。その結果が図4です。図4の右側は、各状態での行動価値関数を示しています。すなわち、赤い矢印は、その状態で、4方向の行動のうち、最大の行動価値(複数個あり得る)があることを示しています。したがって、赤い→をたどると最適経路となります。この学習の行動選択においては、ε-Greedy(単純なランダムではなく)を採用してみました。


 最初に述べたとおり、今回は、自作Javaプログラムの動作を確認するのが主な目的であり、MATLABのReinforcement Toolkitの最も簡単な例題を対象としたに過ぎません。このToolkitは、もっと複雑で規模が大きい問題において、その真価を発揮しそうです。記述の簡便さだけでなく、高性能CPU/GPUや、Hadoopのような分散並列機構もバックで利用できるようになっているようです。

 上記のようなグリッドワールドの問題でも、規模が大きくなると行動状態価値関数(Q値)の計算は次第に困難になることは明らかです。したがって実問題では、「関数近似法」が必要となります。関数近似のひとつとして、deep neural networkを利用するのが深層強化学習(DQN: Deep Q-Network 等)であり、これが現代の主流となっているようです。これについても、調べて書いて行く予定です。

【参考文献】
[1] 大内東、川村秀憲、山本雅人:マルチエージェントシステムの基礎と応用―複雑系工学の計算パラダイム、コロナ社、2002.(特に、3.2 強化学習、pp.70-90)
[2] 以下は、MATLAB(R2019a, R2019b)の強化学習用ツールボックスの説明
・Reinforcement Learning Toolbox
https://jp.mathworks.com/help/reinforcement-learning/index.html?s_tid=CRUX_lftnav
・Train Reinforcement Learning Agent in Basic Grid World
https://jp.mathworks.com/help/reinforcement-learning/ug/train-q-learning-agent-to-solve-basic-grid-world.html
・Create Custom Grid World Environments
https://jp.mathworks.com/help/reinforcement-learning/ug/create-custom-grid-world-environments.html
・Load Predefined Grid World Environments
https://jp.mathworks.com/help/reinforcement-learning/ug/create-custom-grid-world-environments.html


2019年10月8日火曜日

「強化学習」の基礎知識を素早く得るには...

[要旨] 強化学習の基本概念や手法を具体的に(お話としてではなく)学びたいという人は多いと思います。それが、20ページの説明を読めば実現できる!という体験を書きました。

●どのテキストを読めば良いか
 強化学習(Reinforcemnet Learning)をタイトルにしたもの以外に、機械学習関係の書籍の中にも、強化学習が説明されている場合もあります。とりあえず、私のチョイスは以下の3冊です。参考文献[1]は、Suttonによるバイブルとも言われる書籍です。丁寧に書かれていますが、500ページを越える分量にちょっと圧倒されます。これは大相撲で言えば、三役級でしょう。参考文献[2]は、著者の教育研究経験から、「分かりやすさ、易しさ」を重視していますが、後半はかなり高度な内容となっています。少なくとも幕内級〜三役級。

 参考文献[3]、これこそが、今回取り上げた「20ページで具体的に理解できる」書籍なのです。これは、大内東教授(当時北大)らが、2002年に出版したものです。タイトルは、マルチエージェントとなっていますが、第3章第2節「強化学習」20ページ分が素晴らしい。分かりやすく簡潔にして厳密な説明が一貫しており、簡単な例題に対しては自分でプログラムを書いて(書籍には示されていません)確かめることまでできます。これをマスターすれば、少なくとも十両級。


●20頁だけで学ぶ強化学習の基本事項
 この書籍の強化学習で学ぶことは、マルコフ性とマルコフ決定過程、それに基づく状態価値関数とその計算のためのTD(0)学習、行動価値関数とその計算のためのQ学習などです。具体的な数式は図2のとおりですが、ここに出てくる記号、数式で挫折しないように、丁寧かつ一定の厳密さで説明されています。なかなか素晴らしと思います。


 さらに、大規模な問題でQ学習を行う際に問題となる、「知識利用と探索のジレンマ」の説明もあります。Q学習の高速化を図るために、エージェントはランダム方策以外に、グリーディ方策やεグリーディ方策も取れることを、簡単な例で(その長所短所も)説明しています。

●簡単な例題に対してQ学習プログラムを自作する
 基本事項を学んだあとは、簡単な例題で具体的に動作を確認することが重要です。この書籍では、3x3のタイルワールドにおいて、初期状態からゴールまでの最短経路をたどるタスクを取り上げています。図3(a)左側のものですが、ゴール状態に達した時のみ報酬10.0がもらえるようになっています。人間なら、それは最短経路は斜めに進むこと、と直ぐに分かります。この強化学習では、行動価値関数をQ学習で求めることにより、それと同じ結論に達します。図3(a)の右側にその様子を示しました。(右側の図はテキストには載っていません。自作です。)



 次に少しだけ条件を変えてみます。参考文献[1]の例題にあった「ワープ」を取り入れてみます。すなわち、状態1に到達した場合は直ちに(そのステップにおいて)状態4へワープすることにします。それに対するQ学習の結果が、図3(b)右側です。Q(0,NE) = Q(0,E) = 9.0となったこと、また、Q(1,NE) = Q(4, NE) = 10.0となったことから、この場合もQ学習がうまく行ったと言えます。


 図3(a)、図3(b)の右側のような学習結果を得るために、図4のようなJavaプログラムを書きました。50行ほどの短いものです。書籍には、Q学習アルゴリズムはPseudo Codeとして示されていますが、具体的なソースリストは提供されていません。それがまた良いところです。自作することで、強化学習の理解がさらに深まると思いますので。


●今後はどう進めるか
 以上で、小生の強化学習は、幕下から十両まで昇進しました。(ちょっと甘いかも?)その後は、参考文献[2]や[1]がかなり読みやすくなると感じています。また、MATLABやAmazon AWSなどには、強化学習ツール/フレームワークがあり、種々のプロパティを設定するなど、宣言的記述を主とした少ないコーデイングでタスクを実行できる環境を提供しています。今回の基本知識を得た後は、それらも(それほど容易とは思われませんが)活用できるようになるかと思います。

[参考文献]
[1] Richard S. Sutton, Andrew G. Barto : Reinforcement Learning: An Introduction 2nd Edition (Adaptive Computation and Machine Learning series), The MIT Press, 2018.(pdf版は無償公開されているのでびっくりです)
[2] 曽我部東馬:強化学習アルゴリズム入門: 「平均」からはじめる基礎と応用、オーム社、2019.
[3] 大内東、川村秀憲、山本雅人:マルチエージェントシステムの基礎と応用―複雑系工学の計算パラダイム、コロナ社、2002.