
Gymで強化学習㊱Atariゲーム環境:実験結果
前回は、Atariゲームの環境で強化学習を行うための実装を解説しました。今回は、いくつかの実験結果を紹介します。
特に、Atari環境で強化学習を行ったことがある人や、これからやろうと思っている人には参考となるでしょう。
では、さっそく始めましょう。
実験1(terminal_on_life_loss: false)
設定ファイル
これは前回の記事の最後の紹介した設定を使っています。
base:
# 環境とモデル
env_name: "ALE/SpaceInvaders-v5"
device: ""
frame_skip: 4
n_frames: 4
image_crop: null
# モデル
hidden_size: 64
# 訓練
n_seeds: 1
max_steps: 5000000
lr: 2.5e-4 # 学習率
batch_size: 32
weight_decay: 0.001 # L2正則化
amsgrad: true
gradient_clip: 10
reward_clip: 1 # 報酬のクリッピング
reward_scale: 0 # 報酬のスケーリング
termination_penalty: -1 # 終了ペナルティ
terminal_on_life_loss: false # ライフが減ったら終了
# 経験再生メモリ
memory_size: 1000000
priority: "none"
priority_alpha: 0.7
priority_beta_min: 0.5
priority_beta_max: 1.0
# イプシロン貪欲法
start_steps: 50000
epsilon_steps: 1000000
epsilon_max: 1.0
epsilon_min: 0.1
# 割引率
gamma: 0.99
# ターゲットネットワークの更新頻度
target_update_steps: 10000
target_update_tau: 0.0
# 評価
test_steps: 10000
test_max_episodes: 10
dqn-none:
type: dqn
priority: none
dqn-numpy:
type: dqn
priority: numpy
dqn-sumtree:
type: dqn
priority: sumtree
double-none:
type: double
priority: none
double-numpy:
type: double
priority: numpy
double-sumtree:
type: double
priority: sumtree
dueling-double-none:
type: dueling-double
priority: none
lr: 6.25e-5
dueling-double-numpy:
type: dueling-double
priority: numpy
lr: 6.25e-5
dueling-double-sumtree:
type: dueling-double
priority: sumtree
lr: 6.25e-5訓練時間が長いのでDueling DQNのみで実験しました。また、経験再生メモリのサイズが100万と大きいので優先度管理ではSumTreeを使っています。
なお、今記事の全ての実験はDueling DQNのみとなっていますが、DQNやDouble DQNも使えるようにファイル内で設定してあります。また、優先度管理も「なし」(none)、「NumPy」(numpy)、「SumTree」(sumtree)が選べるようになっています。興味がある方は実験してみてください。
なお、この実験では、terminal_on_life_loss: false に設定しています。これは、ゲーム中のライフが減ってもエピソードが終了しないという設定です。スペース・インベーダーでは、ライフが3つあるので、この設定だとライフを失っても報酬としては0を受け取るだけです。AttariProcessing では、この設定がデフォルトなので、まずはこの設定を試します。
実験1を実行するには、以下のコマンドを使います。
python train.py experiments1.yaml dueling-double-sumtreerun-experiments1 フォルダーが作成され、results.dueling-double-sumtree.csv ファイルが保存されます。そこに受け取った報酬の情報が格納されています。
Dueling DQN
実験結果をグラフにすると以下になります。なお、グラフを表示するプログラムは最後に紹介します。

100万ステップあるのでかなりギザギザにはなっています。また、訓練しても少ししか報酬が上がっていません。
これをベースの結果として設定を変えながら比較していきましょう。
実験2(terminal_on_life_loss: true)
設定ファイル
この設定では、terminal_on_life_loss: true とすることでライフを失うとエピソード終了となります。なお、終了ペナルティ(termination_penalty)は、 -1 なのでライフを失うとエピソード終了とともにペナルティとして -1 を受け取ります。
base:
# 環境とモデル
env_name: "ALE/SpaceInvaders-v5"
device: ""
frame_skip: 4
n_frames: 4
image_crop: null
# モデル
hidden_size: 64
# 訓練
n_seeds: 1
max_steps: 5000000
lr: 2.5e-4 # 学習率
batch_size: 32
weight_decay: 0.001 # L2正則化
amsgrad: true
gradient_clip: 10
reward_clip: 1 # 報酬のクリッピング
reward_scale: 0 # 報酬のスケーリング
termination_penalty: -1 # 終了ペナルティ
terminal_on_life_loss: true # ライフが減ったら終了
# 経験再生メモリ
memory_size: 1000000
priority: "none"
priority_alpha: 0.7
priority_beta_min: 0.5
priority_beta_max: 1.0
# イプシロン貪欲法
start_steps: 50000
epsilon_steps: 1000000
epsilon_max: 1.0
epsilon_min: 0.1
# 割引率
gamma: 0.99
# ターゲットネットワークの更新頻度
target_update_steps: 10000
target_update_tau: 0.0
# 評価
test_steps: 10000
test_max_episodes: 10
dqn-none:
type: dqn
priority: none
dqn-numpy:
type: dqn
priority: numpy
dqn-sumtree:
type: dqn
priority: sumtree
double-none:
type: double
priority: none
double-numpy:
type: double
priority: numpy
double-sumtree:
type: double
priority: sumtree
dueling-double-none:
type: dueling-double
priority: none
lr: 6.25e-5
dueling-double-numpy:
type: dueling-double
priority: numpy
lr: 6.25e-5
dueling-double-sumtree:
type: dueling-double
priority: sumtree
lr: 6.25e-5実験2を実行するには、上記の設定を experiments2.yaml として保存し、以下のコマンドを使います。
python train.py experiments2.yaml dueling-double-sumtreeDueling DQN
結果は、このようになりました。実験1と比較しています。

こうして比べると実験2のほうが良い結果を出しています。つまり、terminal_on_life_loss: true の設定が効いていると考えられます。
実験3(terminal_on_life_loss: true、画面の切り取り)
設定ファイル
この設定では、次のように画面の切り取りを指定しました。
image_crop:
top: 5
bottom: 15
left: 3
right: 3これで画面の上下左右の部分が切り取られます。
あとは、実験2と同じです。
base:
# 環境とモデル
env_name: "ALE/SpaceInvaders-v5"
device: ""
frame_skip: 4
n_frames: 4
image_crop:
top: 5
bottom: 15
left: 3
right: 3
# モデル
hidden_size: 64
# 訓練
n_seeds: 1
max_steps: 5000000
lr: 2.5e-4 # 学習率
batch_size: 32
weight_decay: 0.001 # L2正則化
amsgrad: true
gradient_clip: 10
reward_clip: 1 # 報酬のクリッピング
reward_scale: 0 # 報酬のスケーリング
termination_penalty: -1 # 終了ペナルティ
terminal_on_life_loss: true # ライフが減ったら終了
# 経験再生メモリ
memory_size: 1000000
priority: "none"
priority_alpha: 0.7
priority_beta_min: 0.5
priority_beta_max: 1.0
# イプシロン貪欲法
start_steps: 50000
epsilon_steps: 1000000
epsilon_max: 1.0
epsilon_min: 0.1
# 割引率
gamma: 0.99
# ターゲットネットワークの更新頻度
target_update_steps: 10000
target_update_tau: 0.0
# 評価
test_steps: 10000
test_max_episodes: 10
dqn-none:
type: dqn
priority: none
dqn-numpy:
type: dqn
priority: numpy
dqn-sumtree:
type: dqn
priority: sumtree
double-none:
type: double
priority: none
double-numpy:
type: double
priority: numpy
double-sumtree:
type: double
priority: sumtree
dueling-double-none:
type: dueling-double
priority: none
lr: 6.25e-5
dueling-double-numpy:
type: dueling-double
priority: numpy
lr: 6.25e-5
dueling-double-sumtree:
type: dueling-double
priority: sumtree
lr: 6.25e-5
実験3を実行するには、上記の設定を experiments3.yaml として保存し、以下のコマンドを使います。
python train.py experiments3.yaml dueling-double-sumtreeDueling DQN
結果は、このようになりました。実験1、2、3を比較しています。

わかりにくいですが、実験2と3は、ほぼ違いがありません。よって画面の切り取りは、少なくともスペース・インベーダーでは、なくても良さそうです。ただし、もっと長く訓練を続けると違いが出るかも知れません。
以後の実験では、画面の切り取りは行わないことにします。
実験4(terminal_on_life_loss: true、frame_skip: 2)
設定ファイル
この実験では、実験2と同じ設定から、フレームスキップを2にしてみました。フレームを4つスキップするよりもより細かい動きに反応することで成績に変化が出るかを確認します。
base:
# 環境とモデル
env_name: "ALE/SpaceInvaders-v5"
device: ""
frame_skip: 2
n_frames: 4
image_crop: null
# モデル
hidden_size: 64
# 訓練
n_seeds: 1
max_steps: 5000000
lr: 2.5e-4 # 学習率
batch_size: 32
weight_decay: 0.001 # L2正則化
amsgrad: true
gradient_clip: 10
reward_clip: 1 # 報酬のクリッピング
reward_scale: 0 # 報酬のスケーリング
termination_penalty: -1 # 終了ペナルティ
terminal_on_life_loss: true # ライフが減ったら終了
# 経験再生メモリ
memory_size: 1000000
priority: "none"
priority_alpha: 0.7
priority_beta_min: 0.5
priority_beta_max: 1.0
# イプシロン貪欲法
start_steps: 50000
epsilon_steps: 1000000
epsilon_max: 1.0
epsilon_min: 0.1
# 割引率
gamma: 0.99
# ターゲットネットワークの更新頻度
target_update_steps: 10000
target_update_tau: 0.0
# 評価
test_steps: 10000
test_max_episodes: 10
dqn-none:
type: dqn
priority: none
dqn-numpy:
type: dqn
priority: numpy
dqn-sumtree:
type: dqn
priority: sumtree
double-none:
type: double
priority: none
double-numpy:
type: double
priority: numpy
double-sumtree:
type: double
priority: sumtree
dueling-double-none:
type: dueling-double
priority: none
lr: 6.25e-5
dueling-double-numpy:
type: dueling-double
priority: numpy
lr: 6.25e-5
dueling-double-sumtree:
type: dueling-double
priority: sumtree
lr: 6.25e-5
実験4を実行するには、上記の設定を experiments4.yaml として保存し、以下のコマンドを使います。
python train.py experiments4.yaml dueling-double-sumtreeDueling DQN
結果は、このようになりました。実験2と4を比較しています。

結果としては、フレームスキップが2である実験4のほうが成績がかなり悪いです。
実は、実験1と比べても悪い成績になっています。

よって、スペース・インベーダーでは、フレームスキップを2に設定するのはよくないのがわかりました。
実験5(terminal_on_life_loss: true、termination_penalty: -2)
設定ファイル
今の所は、実験2が一番の成績です。実験5では、終了ペナルティを -1 から -2 に変更しました。終了ペナルティによって報酬にどのような差が出るでしょうか。
base:
# 環境とモデル
env_name: "ALE/SpaceInvaders-v5"
device: ""
frame_skip: 4
n_frames: 4
image_crop: null
# モデル
hidden_size: 64
# 訓練
n_seeds: 1
max_steps: 5000000
lr: 2.5e-4 # 学習率
batch_size: 32
weight_decay: 0.001 # L2正則化
amsgrad: true
gradient_clip: 10
reward_clip: 1 # 報酬のクリッピング
reward_scale: 0 # 報酬のスケーリング
termination_penalty: -2 # 終了ペナルティ
terminal_on_life_loss: true # ライフが減ったら終了
# 経験再生メモリ
memory_size: 1000000
priority: "none"
priority_alpha: 0.7
priority_beta_min: 0.5
priority_beta_max: 1.0
# イプシロン貪欲法
start_steps: 50000
epsilon_steps: 1000000
epsilon_max: 1.0
epsilon_min: 0.1
# 割引率
gamma: 0.99
# ターゲットネットワークの更新頻度
target_update_steps: 10000
target_update_tau: 0.0
# 評価
test_steps: 10000
test_max_episodes: 10
dqn-none:
type: dqn
priority: none
dqn-numpy:
type: dqn
priority: numpy
dqn-sumtree:
type: dqn
priority: sumtree
double-none:
type: double
priority: none
double-numpy:
type: double
priority: numpy
double-sumtree:
type: double
priority: sumtree
dueling-double-none:
type: dueling-double
priority: none
lr: 6.25e-5
dueling-double-numpy:
type: dueling-double
priority: numpy
lr: 6.25e-5
dueling-double-sumtree:
type: dueling-double
priority: sumtree
lr: 6.25e-5
実験5を実行するには、上記の設定を experiments5.yaml として保存し、以下のコマンドを使います。
python train.py experiments5.yaml dueling-double-sumtreeDueling DQN
結果は、このようになりました。実験2と5を比較しています。

ほとんど差がないようです。
ただし、ログを見ていると評価の平均報酬の最高が実験2では 604.5 で、実験5では 630 でした。たまたまかも知れませんが、これをもって実験5の設定を優位として、ここからのベースとして採用することにしました。
実験6(terminal_on_life_loss: true、termination_penalty: -5)
設定ファイル
もっとペナルティを増やしたらどうでしょうか。実験6では終了ペナルティを−5としました。
base:
# 環境とモデル
env_name: "ALE/SpaceInvaders-v5"
device: ""
frame_skip: 4
n_frames: 4
image_crop: null
# モデル
hidden_size: 64
# 訓練
n_seeds: 1
max_steps: 5000000
lr: 2.5e-4 # 学習率
batch_size: 32
weight_decay: 0.001 # L2正則化
amsgrad: true
gradient_clip: 10
reward_clip: 1 # 報酬のクリッピング
reward_scale: 0 # 報酬のスケーリング
termination_penalty: -5 # 終了ペナルティ
terminal_on_life_loss: true # ライフが減ったら終了
# 経験再生メモリ
memory_size: 1000000
priority: "none"
priority_alpha: 0.7
priority_beta_min: 0.5
priority_beta_max: 1.0
# イプシロン貪欲法
start_steps: 50000
epsilon_steps: 1000000
epsilon_max: 1.0
epsilon_min: 0.1
# 割引率
gamma: 0.99
# ターゲットネットワークの更新頻度
target_update_steps: 10000
target_update_tau: 0.0
# 評価
test_steps: 10000
test_max_episodes: 10
dqn-none:
type: dqn
priority: none
dqn-numpy:
type: dqn
priority: numpy
dqn-sumtree:
type: dqn
priority: sumtree
double-none:
type: double
priority: none
double-numpy:
type: double
priority: numpy
double-sumtree:
type: double
priority: sumtree
dueling-double-none:
type: dueling-double
priority: none
lr: 6.25e-5
dueling-double-numpy:
type: dueling-double
priority: numpy
lr: 6.25e-5
dueling-double-sumtree:
type: dueling-double
priority: sumtree
lr: 6.25e-5
実験6を実行するには、上記の設定を experiments6.yaml として保存し、以下のコマンドを使います。
python train.py experiments6.yaml dueling-double-sumtreeDueling DQN
結果は、このようになりました。実験5と6を比較しています。

実験6の結果は、実験5を下回りました。また、訓練が不安定になっているように見えます。これは、ペナルティを大きくし過ぎたためだと考えられます(それしか変更していないので)。報酬のクリッピングは、成績に影響があり重要なのがわかります。
よって、今回も勝者は実験5となりました。
実験7(terminal_on_life_loss: true、termination_penalty: -3)
設定ファイル
しつこいようですが、終了ペナルティを -3 として実験することにしました。実験5では -2 なので、もう少しだけペナルティを増やしたらどうなるかを確認します。
base:
# 環境とモデル
env_name: "ALE/SpaceInvaders-v5"
device: ""
frame_skip: 4
n_frames: 4
image_crop: null
# モデル
hidden_size: 64
# 訓練
n_seeds: 1
max_steps: 5000000
lr: 2.5e-4 # 学習率
batch_size: 32
weight_decay: 0.001 # L2正則化
amsgrad: true
gradient_clip: 10
reward_clip: 1 # 報酬のクリッピング
reward_scale: 0 # 報酬のスケーリング
termination_penalty: -3 # 終了ペナルティ
terminal_on_life_loss: true # ライフが減ったら終了
# 経験再生メモリ
memory_size: 1000000
priority: "none"
priority_alpha: 0.7
priority_beta_min: 0.5
priority_beta_max: 1.0
# イプシロン貪欲法
start_steps: 50000
epsilon_steps: 1000000
epsilon_max: 1.0
epsilon_min: 0.1
# 割引率
gamma: 0.99
# ターゲットネットワークの更新頻度
target_update_steps: 10000
target_update_tau: 0.0
# 評価
test_steps: 10000
test_max_episodes: 10
dqn-none:
type: dqn
priority: none
dqn-numpy:
type: dqn
priority: numpy
dqn-sumtree:
type: dqn
priority: sumtree
double-none:
type: double
priority: none
double-numpy:
type: double
priority: numpy
double-sumtree:
type: double
priority: sumtree
dueling-double-none:
type: dueling-double
priority: none
lr: 6.25e-5
dueling-double-numpy:
type: dueling-double
priority: numpy
lr: 6.25e-5
dueling-double-sumtree:
type: dueling-double
priority: sumtree
lr: 6.25e-5
実験7を実行するには、上記の設定を experiments7.yaml として保存し、以下のコマンドを使います。
python train.py experiments7.yaml dueling-double-sumtreeDueling DQN
結果は、このようになりました。実験5と7を比較しています。

ご覧の通り、実験7の成績は悪くなっています。よって、終了ペナルティは -2 ということで決着しました。
ここでも実験5の勝利となしました。
実験8(terminal_on_life_loss: true、termination_penalty: -2、reward_clip: 0、reward_scale: 0.01)
実験8では、報酬クリッピングの代わりに、報酬のスケーリングを使います。
reward_clip: 0 # 報酬のクリッピング
reward_scale: 0.01 # 報酬のスケーリング全ての報酬(終了ペナルティは除く)を0.01倍することで、報酬が大き過ぎないようにしています。UFO(Command Ship、指揮船)を撃ち落とすと200ポイントなので、報酬のスケーリングにより2 ポイントになります。ただし、エイリアンのスコアは、5ポイントから30ポイントなので、0.05 から0.3 ポイントになります。ちなみに、スコアなどの詳細はこちらを参照しました。
これによって、報酬の大きさを抑えつつも撃ち落とした対象によって差が出るようになっています。
base:
# 環境とモデル
env_name: "ALE/SpaceInvaders-v5"
device: ""
frame_skip: 4
n_frames: 4
image_crop: null
# モデル
hidden_size: 64
# 訓練
n_seeds: 1
max_steps: 5000000
lr: 2.5e-4 # 学習率
batch_size: 32
weight_decay: 0.001 # L2正則化
amsgrad: true
gradient_clip: 10
reward_clip: 0 # 報酬のクリッピング
reward_scale: 0.01 # 報酬のスケーリング
termination_penalty: -2 # 終了ペナルティ
terminal_on_life_loss: true # ライフが減ったら終了
# 経験再生メモリ
memory_size: 1000000
priority: "none"
priority_alpha: 0.7
priority_beta_min: 0.5
priority_beta_max: 1.0
# イプシロン貪欲法
start_steps: 50000
epsilon_steps: 1000000
epsilon_max: 1.0
epsilon_min: 0.1
# 割引率
gamma: 0.99
# ターゲットネットワークの更新頻度
target_update_steps: 10000
target_update_tau: 0.0
# 評価
test_steps: 10000
test_max_episodes: 10
dqn-none:
type: dqn
priority: none
dqn-numpy:
type: dqn
priority: numpy
dqn-sumtree:
type: dqn
priority: sumtree
double-none:
type: double
priority: none
double-numpy:
type: double
priority: numpy
double-sumtree:
type: double
priority: sumtree
dueling-double-none:
type: dueling-double
priority: none
lr: 6.25e-5
dueling-double-numpy:
type: dueling-double
priority: numpy
lr: 6.25e-5
dueling-double-sumtree:
type: dueling-double
priority: sumtree
lr: 6.25e-5
実験8を実行するには、上記の設定を experiments8.yaml として保存し、以下のコマンドを使います。
python train.py experiments8.yaml dueling-double-sumtreeDueling DQN
結果は、このようになりました。実験5と8を比較しています。

結果として訓練がだいぶ不安定になっています。報酬スケーリングは、よくないのが分かりました。よって、報酬のクリッピングを1に設定するほうが良いという結果になりました。
よって、今回も実験5が勝者です。
実験9(terminal_on_life_loss: true、termination_penalty: -2、priority_alpha: 0.6、priority_beta_min: 0.4)
今回は、ちょっと焦点を変えて、優先度管理のパラメータをいじってみました。
priority_alpha: 0.7
priority_beta_min: 0.5から、次のように変更します。
priority_alpha: 0.6
priority_beta_min: 0.4どのような変化が起きるのか、確認します。
base:
# 環境とモデル
env_name: "ALE/SpaceInvaders-v5"
device: ""
frame_skip: 4
n_frames: 4
image_crop: null
# モデル
hidden_size: 64
# 訓練
n_seeds: 1
max_steps: 5000000
lr: 2.5e-4 # 学習率
batch_size: 32
weight_decay: 0.001 # L2正則化
amsgrad: true
gradient_clip: 10
reward_clip: 1 # 報酬のクリッピング
reward_scale: 0 # 報酬のスケーリング
termination_penalty: -2 # 終了ペナルティ
terminal_on_life_loss: true # ライフが減ったら終了
# 経験再生メモリ
memory_size: 1000000
priority: "none"
priority_alpha: 0.6
priority_beta_min: 0.4
priority_beta_max: 1.0
# イプシロン貪欲法
start_steps: 50000
epsilon_steps: 1000000
epsilon_max: 1.0
epsilon_min: 0.1
# 割引率
gamma: 0.99
# ターゲットネットワークの更新頻度
target_update_steps: 10000
target_update_tau: 0.0
# 評価
test_steps: 10000
test_max_episodes: 10
dqn-none:
type: dqn
priority: none
dqn-numpy:
type: dqn
priority: numpy
dqn-sumtree:
type: dqn
priority: sumtree
double-none:
type: double
priority: none
double-numpy:
type: double
priority: numpy
double-sumtree:
type: double
priority: sumtree
dueling-double-none:
type: dueling-double
priority: none
lr: 6.25e-5
dueling-double-numpy:
type: dueling-double
priority: numpy
lr: 6.25e-5
dueling-double-sumtree:
type: dueling-double
priority: sumtree
lr: 6.25e-5
実験9を実行するには、上記の設定を experiments9.yaml として保存し、以下のコマンドを使います。
python train.py experiments9.yaml dueling-double-sumtreeDueling DQN
結果は、このようになりました。実験5と9を比較しています。

ほぼ差はないと言えるでしょう。スペース・インベーダーの環境では、優先度の設定を多少いじっても変化は出ませんでした。
もっと訓練を長く行うと異なる結果になる可能性はありますが、今回は実験5から設定を変更する理由は見当たりませんでした。
実験10(実験5でmax_steps: 50000000)
設定ファイル
他にもたくさん試すことはありますが、ここまで実験5が一番良い成績を出したので、最大ステップ数を500万から5000万に増やしてどのくらいまで成績が伸びるのかを確認します。
base:
# 環境とモデル
env_name: "ALE/SpaceInvaders-v5"
device: ""
frame_skip: 4
n_frames: 4
image_crop: null
# モデル
hidden_size: 64
# 訓練
n_seeds: 1
max_steps: 50000000
lr: 2.5e-4 # 学習率
batch_size: 32
weight_decay: 0.001 # L2正則化
amsgrad: true
gradient_clip: 10
reward_clip: 1 # 報酬のクリッピング
reward_scale: 0 # 報酬のスケーリング
termination_penalty: -2 # 終了ペナルティ
terminal_on_life_loss: true # ライフが減ったら終了
# 経験再生メモリ
memory_size: 1000000
priority: "none"
priority_alpha: 0.7
priority_beta_min: 0.5
priority_beta_max: 1.0
# イプシロン貪欲法
start_steps: 50000
epsilon_steps: 1000000
epsilon_max: 1.0
epsilon_min: 0.1
# 割引率
gamma: 0.99
# ターゲットネットワークの更新頻度
target_update_steps: 10000
target_update_tau: 0.0
# 評価
test_steps: 10000
test_max_episodes: 10
dqn-none:
type: dqn
priority: none
dqn-numpy:
type: dqn
priority: numpy
dqn-sumtree:
type: dqn
priority: sumtree
double-none:
type: double
priority: none
double-numpy:
type: double
priority: numpy
double-sumtree:
type: double
priority: sumtree
dueling-double-none:
type: dueling-double
priority: none
lr: 6.25e-5
dueling-double-numpy:
type: dueling-double
priority: numpy
lr: 6.25e-5
dueling-double-sumtree:
type: dueling-double
priority: sumtree
lr: 6.25e-5実験10を実行するには、上記の設定を experiments10.yaml として保存し、以下のコマンドを使います。
python train.py experiments10.yaml dueling-double-sumtreeDueling DQN
結果は、このようになりました。と言いたいところですが、まだ、訓練実行途中です。38,540,000ステップぐらいまで完了しています。50,000,000ステップが完了したら、この記事を更新して掲示板からお知らせします。これまでの評価における最大の平均報酬は、すでに1,000を越えていますが、学習はかなりゆったりとしている印象です。もう5日ぐらい走らせたままです。まだ、しばらく掛かりそうです。
2023年9月1日10時頃に、やっと実験10が終了しました。結果は以下の通りです。

スコアの最大値は1750を超えていますが平均で見ると1250弱あたりになりました。まだ続ければ平均報酬も上昇しそうではあります。特に最後の方は低いスコアが出る確率が下がってきています。
これだけ長く訓練を行なって学習が不安定にならないのは、実験6で見たように報酬クリップによるところが大きいでしょう。イプシロン・グリーディの最低値を 0.1 にしてあるので長く訓練をする程に様々な状態と行動の組み合わせに巡り合う可能性があるため、長時間の訓練をする必要があるのも頷けます。
まだ、色々と実験できることはありますが、今回はこれにて終了とします。設定ファイルを変えるだけで様々なケースを試せるので是非試してください。
実験結果のグラフ表示
ソースコード
import argparse
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import re
# コマンドライン引数の設定
parser = argparse.ArgumentParser()
parser.add_argument("result_files", type=argparse.FileType('r'), nargs="+")
parser.add_argument("--max_score", type=int, default=1000)
args = parser.parse_args()
labeled_files = []
for result_file in args.result_files:
path_comps = os.path.split(result_file.name)
# match a number
number = re.search(r'(\d+)', path_comps[-2]).group(1)
name = re.search(r'results\.(.*)\.csv', path_comps[-1]).group(1)
print(number, name)
labeled_files.append((result_file, number, name.title().replace("-", " ")))
labeled_files = sorted(labeled_files, key=lambda x: x[1] + x[2])
# 図を描画する
plt.style.use('ggplot')
plt.figure(figsize=(10, 7))
# 順番に結果を描画する
for i, (result_file, number, name) in enumerate(labeled_files):
df = pd.read_csv(result_file)
steps = df.columns.astype(int).values
label = f"Experiment-{number}: {name}"
# 75パーセンタイル、メジアン、25パーセンタイル
upper_bound = df.quantile(0.75, axis=0).values
median_line = df.quantile(0.50, axis=0).values
lower_bound = df.quantile(0.25, axis=0).values
# 色を設定する
color = plt.cm.tab10(i)
plt.plot(steps, median_line, label=label, color=color, linewidth=1.0)
pos = len(steps) // len(labeled_files) * i + 20
plt.annotate(label,
xy=(steps[pos], median_line[pos]),
xytext=(10, 200),
textcoords='offset points',
color=color,
size=12,
arrowprops=dict(
color=color,
alpha=0.3,
width=1,
headwidth=5)
)
plt.fill_between(steps, lower_bound, upper_bound, color=color, alpha=0.1)
plt.title("Reward History")
plt.xlabel("Steps")
plt.ylabel("Reward")
plt.ylim(0, args.max_score)
plt.tight_layout()
plt.savefig("results.png", bbox_inches="tight")
plt.show()
この内容を visualize_results.py に保存してください。
実行の方法
実験を行うのと同じPython環境で次のように実行します。
python visualize_results.py <結果データ.csv>たとえば、実験1の dueling-double-sumtree の結果をグラフ表示するには、以下のように実行します。
python visualize_results.py \
runs-experiments1/results.dueling-double-sumtree.csvまた、複数のファイルを指定することもできます。
python visualize_results.py \
runs-experiments1/results.dueling-double-sumtree.csv \
runs-experiments2/results.dueling-double-sumtree.csvワイルドカードを使うこともできます。以下では全ての実行フォルダから dueling-double-sumtree の実行結果を表示します。
python visualize_results.py \
runs-experiments*/results.dueling-double-sumtree-*.csvただし、グラフに入れるデータが多すぎると表示がグチャグチャになるので3つぐらいまでにしたほうが読みやすいです。
実験10のようにスコアが1000を超えてくる場合は、次のように上限を設定することもできます。
python visualize_results.py \
runs-experiments10/results.dueling-double-sumtree.csv --max_score 2000テストの実行
ソースコード
import argparse
import gymnasium as gym
import logging
import numpy as np
import pandas as pd
import torch
import yaml
from gymnasium.wrappers import AtariPreprocessing, FrameStack
# train.pyからのコードを使う
from train import Config, make_env, make_device, make_q_network
logging.basicConfig(level=logging.INFO, format="%(message)s")
logger = logging.getLogger(__name__)
def main():
# 引数の設定
parser = argparse.ArgumentParser()
parser.add_argument("model_path", type=str, help="path to model.pth")
parser.add_argument("--no_render", action="store_true")
parser.add_argument("--max_episodes", type=int, default=10)
parser.add_argument("--device" , type=str, default="")
args = parser.parse_args()
# 設定ファイルのパスをモデルのファイル名から作成
# 例: model.*.pth -> config.*.yaml
config_path = args.model_path.replace("model", "config").replace("pth", "yaml")
# 設定を読み込む
with open(config_path) as f:
config = Config(**yaml.safe_load(f))
if args.device != "":
config.device = args.device
# 新しくGym環境を作成してシードを設定する
env = make_env(config, args.no_render)
# デバイスを作成する
device = make_device(config.device)
# ポリシーネットワークを作成し、モデルのパラメータを読み込む
policy_network = make_q_network(env,config)
policy_network.load_state_dict(torch.load(args.model_path))
policy_network.to(device)
# エピソードの報酬を記録する
rewards = []
for episode in range(args.max_episodes):
total_reward = 0
# 環境を初期化する
observation, _ = env.reset()
steps = 0
while True:
# ポリシーネットワークを使って行動を選択する
with torch.no_grad():
state = torch.from_numpy(np.array(observation)).to(device)
q_values = policy_network(state.unsqueeze(0))
action = q_values.argmax().cpu().item()
# 行動を実行して、次の状態と報酬を観測する
observation, reward, terminated, truncated, info = env.step(action)
total_reward += reward
steps += 1
# 環境が終了したら次のエピソードに移る
if terminated or truncated:
break
# エピソードの報酬を記録する
rewards.append(total_reward)
# ログを出力する
logger.info(f"Episode: {episode + 1:3d} Steps: {steps:6d} Reward: {total_reward:7.1f} Terminated: {terminated} Truncated: {truncated} Info: {info}")
# エピソードの報酬の平均と標準偏差を計算する
rewards = np.array(rewards)
mean = rewards.mean()
std = rewards.std()
logger.info(f"Mean Reward: {mean:7.1f}, Std: {std:7.1f}")
if __name__ == "__main__":
main()
この内容を test.py に保存してください。
実行の方法
実験を行うのと同じPython環境で次のように実行します。
python test.py <保存されたモデル.pth>たとえば、実験1の dueling-double-sumtree の訓練で保存さらたモデルでテストを実行するには、以下のように実行します。
python test.py runs-experiments1/model.dueling-double-sumtree.pth 
訓練中でも、評価による平均報酬が最高値を出すと、モデルファイルが保存されるのでその時のエージェントをテストすることができます。
次回予告
今回で、DQN関連の強化学習は一旦終わりにします。振り返ってみると、これまでずっと、行動価値を最大化する行動選択を行う手法を解説してきました。しかし、最終的な目的は最適な行動を選ぶことであり、行動価値の計算はそこへたどり着くための手段です。
次回からは、異なるタイプの強化学習として、ポリシー勾配法(方策勾配法、Policy Gradient)についての解説を始めます。ポリシー勾配法では、行動価値を最大化する行動を選ぶのではなく、直接的に行動を選びます。よって、これまで見てきた手法とは異なる流派の強化学習が登場してきます。
お楽しみに!
(続く)