実現したいこと
ポケモンのalphazero(モンテカルロ、deeplearning、強化学習)を作っています。ループでなぜか一回多く行われてしまいます。エラーを解決したいです。
発生している問題・分からないこと
ループでなぜか一回多く行われてしまいます。エラーを解決したいです。そのためエラーが発生しています
エラーメッセージ
error
1WARNING:tensorflow:No training configuration found in the save file, so the model was *not* compiled. Compile it manually. 21/1 [==============================] - 0s 110ms/step 3battle実行されました 40 51 6モンテカルロ 6 7c1 (Jolteon(271), BodySlam, [Jolteon(271)]) 8サンダース が技のしかかりをつかった! 9こうかはいまひとつ... 0.5 10サイドン が20をうけた 11❤️ サイドン 残りHP 331 12サイドン技いわなだれを使った! 13急所に当たりました! 14こうかはばつぐんだ! 1.5 15サンダースが271を受けた 16⭐️ サンダース 残りHP 0 17len(self.child_nodes) 1 18argmax 0 19turn 1 20len(pucb_values) 1 21pucb_values [array([0., 0., 0., 0.], dtype=float32)] 22index <class 'numpy.int64'> 23index 0 24len(self.child_nodes) 1 25self.child_nodes [<__main__.pv_mcts_scores.<locals>.Node object at 0x17a4326d0>] 26len(self.child_nodes) 1 27argmax 2 28turn 2 29len(pucb_values) 1 30pucb_values [array([1. , 1. , 1.5, 1. ], dtype=float32)] 31index <class 'numpy.int64'> 32index 2 33len(self.child_nodes) 1 34self.child_nodes [<__main__.pv_mcts_scores.<locals>.Node object at 0x17a4326d0>] 35--------------------------------------------------------------------------- 36IndexError Traceback (most recent call last) 37Cell In[91], line 44 38 42 c2hp=player1[0].actual_hp 39 43 result=((c1,-1,-1,c1hp),(c2,-1,-1,c2hp)) 40---> 44 next_action=action1(result) 41 45 winner = battle.get_winner() 42 46 #ゲーム終了時 43 44Cell In[89], line 117, in pv_mcts_action.<locals>.pv_mcts_action(state) 45 116 def pv_mcts_action(state): 46--> 117 scores = pv_mcts_scores(model, state, temperature,winner) 47 118 rng=np.random.default_rng() 48 119 return rng.choice([0,1,2,3], p=scores) 49 50Cell In[89], line 102, in pv_mcts_scores(model, state, temperature, winner) 51 100 # 複数回の評価の実行 52 101 for _ in range(PV_EVALUATE_COUNT): 53--> 102 root_node.evaluate() 54 104 # 合法手の確率分布 55 105 scores = nodes_to_scores(root_node.child_nodes) 56 57Cell In[89], line 64, in pv_mcts_scores.<locals>.Node.evaluate(self) 58 59 return value 59 61 # 子ノードが存在する時 60 62 else: 61 63 # アーク評価値が最大の子ノードの評価で価値を取得 62---> 64 value = self.next_child_node().evaluate() 63 66 # 累計価値と試行回数の更新 64 67 self.w += value 65 66Cell In[89], line 95, in pv_mcts_scores.<locals>.Node.next_child_node(self) 67 93 print("len(self.child_nodes)",len(self.child_nodes)) 68 94 print("self.child_nodes",self.child_nodes) 69---> 95 return self.child_nodes[a] 70 71IndexError: list index out of range
該当のソースコード
python
1from dual_network import DN_INPUT_SHAPE 2from math import sqrt 3from tensorflow.keras.models import load_model 4from pathlib import Path 5import numpy as np 6import battle 7from battle import Battle 8import pokedex as p 9import moves as m 10 11# パラメータの準備 12PV_EVALUATE_COUNT = 50 # 1推論あたりのシミュレーション回数(本家は1600) 13 14# 推論 15def predict(model, state): 16 # 推論のための入力データのシェイプの変換 17 x=np.array(state) 18 x=x.reshape(1,4,2) 19 20 # 推論 21 y=model.predict(x,batch_size=1) 22 23 # 方策の取得 24 policies=y[0][0:4] 25 26 # 価値の取得 27 value=y[1][0] 28 29 return policies, value 30 31# ノードのリストを試行回数のリストに変換 32def nodes_to_scores(nodes): 33 scores = [] 34 for c in nodes: 35 scores.append(c.n) 36 return scores 37 38# モンテカルロ木探索のスコアの取得 39#def pv_mcts_scores(model, p1_is,p1_mae_action,p1_took_damage,p1_nokorihp,p1_is,p2_mae_action,p2_took_damage,p2_nokorihp, temperature): #stateに8つの状態 40def pv_mcts_scores(model, state, temperature,winner=None): #stateに8つの状態 41# モンテカルロ木探索のノードの定義 42 class Node: 43 player1=[ 44 p.Jolteon([m.BodySlam(),m.DoubleKick(),m.PinMissle(),m.Thunderbolt()]) 45 ] 46 47 player2=[ 48 p.Rhydon([m.Earthquake(), m.RockSlide(), m.Surf(), m.BodySlam()]) 49 ] 50 51 # ノードの初期化 52 def __init__(self, state, p,winner): 53 self.state = state # 状態 54 self.p = p # 方策 55 self.w = 0 # 累計価値 56 self.n = 0 # 試行回数 57 self.winner=winner 58 self.child_nodes = None # 子ノード群 59 (self.p1_is,self.p1_mae_action,self.p1_took_damage,self.p1_nokorihp),(self.p1_is,self.p2_mae_action,self.p2_took_damage,self.p2_nokorihp)=state 60 self.turn=0 61 62 # 局面の価値の計算 63 def evaluate(self): #Battle が入る 64 # ゲーム終了時 65 if self.winner is not None: 66 # 勝敗結果で価値を取得 67 #print("hplen",len(self.p1_nokorihp)) 68 battle=Battle(player1,player2) 69 value = 0 if self.winner == player1 else -1 70 71 # 累計価値と試行回数の更新 72 self.w += value 73 self.n += 1 74 return value 75 76 # 子ノードが存在しない時 77 if not self.child_nodes: 78 # ニューラルネットワークの推論で方策と価値を取得 79 policies, value = predict(model, state) 80 81 # 累計価値と試行回数の更新 82 self.w += value 83 self.n += 1 84 85 86 # 子ノードの展開 87 self.child_nodes = [] 88 a=[6,7,8,9] 89 for action, policy in zip(a, policies): 90 battle=Battle(player1,player2) 91 zyoutai=battle.forward_step(self.p1_nokorihp,self.p2_nokorihp,action) 92 winner = battle.get_winner() 93 self.child_nodes.append(Node(zyoutai, policy,winner)) 94 95 96 return value 97 98 # 子ノードが存在する時 99 else: 100 # アーク評価値が最大の子ノードの評価で価値を取得 101 value = self.next_child_node().evaluate() 102 103 # 累計価値と試行回数の更新 104 self.w += value 105 self.n += 1 106 return value 107 108 # アーク評価値が最大の子ノードを取得 109 def next_child_node(self): 110 # アーク評価値の計算 111 C_PUCT = 1.0 112 t = sum(nodes_to_scores(self.child_nodes)) 113 pucb_values = [] 114 #print("前 child_nodes",len(self.child_nodes)) 115 for child_node in self.child_nodes: 116 pucb_values.append((-child_node.w / child_node.n if child_node.n else 0.0) + 117 C_PUCT * child_node.p * sqrt(t) / (1 + child_node.n)) 118 self.turn+=1 119 120 # アーク評価値が最大の子ノードを返す 121 print("argmax",np.argmax(pucb_values)) 122 print("turn",self.turn) 123 print("len(pucb_values)",len(pucb_values)) 124 print("pucb_values",pucb_values) 125 index=np.argmax(pucb_values) 126 a = index.item() 127 print("index",type(index)) 128 print("index",index) 129 print("len(self.child_nodes)",len(self.child_nodes)) 130 print("self.child_nodes",self.child_nodes) 131 return self.child_nodes[a] 132 133 # 現在の局面のノードの作成 134 root_node = Node(state, 0,winner) 135 136 # 複数回の評価の実行 137 for _ in range(PV_EVALUATE_COUNT): 138 root_node.evaluate() 139 140 # 合法手の確率分布 141 scores = nodes_to_scores(root_node.child_nodes) 142 if temperature == 0: # 最大値のみ1 143 action = np.argmax(scores) 144 scores = np.zeros(len(scores)) 145 scores[action] = 1 146 else: # ボルツマン分布でバラつき付加 147 scores = boltzman(scores, temperature) 148 return scores 149 150# モンテカルロ木探索で行動選択 151def pv_mcts_action(model, temperature=0): 152 def pv_mcts_action(state): 153 scores = pv_mcts_scores(model, state, temperature,winner) 154 rng=np.random.default_rng() 155 return rng.choice([0,1,2,3], p=scores) 156 return pv_mcts_action 157 158# ボルツマン分布 159def boltzman(xs, temperature): 160 xs = [x ** (1 / temperature) for x in xs] 161 return [x / sum(xs) for x in xs]
python
1import moves as m 2import pokedex as p 3from damage import calculate_damage 4 5# 動作確認 6if __name__ == '__main__': 7 # モデルの読み込み 8 path = sorted(Path('./model').glob('*.h5'))[-1] 9 model = load_model(str(path)) 10 winner=None 11 # 状態の生成 12 player1=[ 13 p.Jolteon([m.BodySlam(),m.DoubleKick(),m.PinMissle(),m.Thunderbolt()]) 14 ] 15 16 player2=[ 17 p.Rhydon([m.Earthquake(), m.RockSlide(), m.Surf(), m.BodySlam()]) 18 ] 19 20 battle=Battle(player1,player2) 21 22 # モンテカルロ木探索で行動取得を行う関数の生成 23 action1 = pv_mcts_action(model, 1.0) 24 25 result=None 26 while True: 27 if result is not None: 28 if winner is not None: 29 print("バトルは終了しました") 30 break 31 else: 32 result=battle.forward_step(action=next_action) 33 next_action=action1(result) 34 else: 35 #1番目(resultない) 36 #result= battle.forward_step() 37 if player1[0].spe > player2[0].spe: 38 c1=1 39 c2=0 40 c1hp=player1[0].actual_hp 41 c2hp=player2[0].actual_hp 42 else: 43 c1=0 44 c2=1 45 c1hp=player2[0].actual_hp 46 c2hp=player1[0].actual_hp 47 result=((c1,-1,-1,c1hp),(c2,-1,-1,c2hp)) 48 next_action=action1(result) 49 winner = battle.get_winner() 50 #ゲーム終了時 51 if winner is not None or battle.turn > 500: 52 break
試したこと・調べたこと
- teratailやGoogle等で検索した
- ソースコードを自分なりに変更した
- 知人に聞いた
- その他
上記の詳細・結果
ループでなぜか2回実行されていることがわかりました。
補足
stateはシェイプ(4,2)
> ループでなぜか2回実行されていることがわかりました。
どうやってそれを確かめましたか?
参考
AlphaZero 深層学習・強化学習・探索 人工知能プログラミング実践入門
self.turnを表示してみると一回のところが2になってました。
> self.turnを表示してみると
すでにソースに書いてある print("turn",self.turn) の行の話ですか?
それともそことは別にself.turnを表示するコードをどこかに書いたということですか? だとしたらそれはどこですか?
print("turn",self.turn) の行の話です。
(問題点がよくわからなくなったのでいったんコメント削除します)
整理すると
引用の"エラーメッセージ"のブロックで 28行目に turn 2 とでているが、意図した動作ではない。それを「ループが意図したものより1回多い」のだろうと**推測し**、質問で「ループでなぜか一回多く行われてしまいます」と **表現した**
エラーが起きているという**事実に**対して、その原因が上記の意図しない動作に依るものと **推測した**
という感じですかね
(ちょっと斜め読みしただけだと、「1回のループで2個Nodeが作られた」可能性とか、「木構造のコードのバグで単一のNodeのturnが意図せず加算された」可能性とかを排除できなかったので……)
そうです。self.turnは本来は1だと思います
Battle クラスの内容が不明なので質問に追記してもらえると原因が判明するかもしれません。
battle=Battle(player1,player2)
:
winner = battle.get_winner()
#ゲーム終了時
そもそも、どの for 文のことを言っているのでしょう。
for child_node in self.child_nodes:
の部分です
文字数が上限に達したのでこちらに追記します。クラスbattle、インデントがなくなってしまい申し訳ないです。
import moves as m
import pokedex as p
from damage import calculate_damage
from random import randint
def choose_action(self) :#ランダム攻撃
return randint(6,9)
#raise NotImplementedError
def get_spe_ordered_pokemon(c1, c2) :
if c1[0].spe > c2[0].spe:
return (c1, c2)
if c1[0].spe < c2[0].spe:
return (c2, c1)
return (c1, c2) if random() > 0.5 else (c2, c1)
def get_available_pokemons(pokemons):
return [p for p in pokemons if p.actual_hp > 0]
def is_dead(pokemons):
return len(get_available_pokemons(pokemons)) == 0
def is_move(action) -> bool:
return action >= 6
class Battle:
def __init__(self,player1,player2):
self.player1=player1
self.player2=player2
self.turn = 0
def forward_step(self,hp1=None,hp2=None,action=None):
print("battle実行されました")
self.turn += 1
if action is not None:
action1=action
else:
#1回目の時
if(action=-1)
action1 = choose_action(self.player2)
action2 = choose_action(self.player1)
#result=(action1,action2,player1_took_damage,player2_took_damage)
active_pokemon1=self.player1[0]
active_pokemon2=self.player2[0]
print(action1 - 6)
print(action2 - 6)
print("モンテカルロ",action)
if is_move(action1) and is_move(action2):
# to handle both player choose a move
c1, c2 = get_spe_ordered_pokemon(
(active_pokemon1, active_pokemon1.actual_moves[action1 - 6], self.player1),
(active_pokemon2, active_pokemon2.actual_moves[action2 - 6], self.player2),
)
print("c1",c1)
#print(f"{c1[2]}'の {c1[0]} が技{c1[1]}をつかった!")
print(f"{c1[0].name_ja} が技{c1[1].name_ja}をつかった!")
damage = calculate_damage(c1[0], c2[0], c1[1])
took_damage1=damage
if hp1 is not None and c1 == self.player1:
c1[0].actual_hp=hp1
c2[0].actual_hp=hp2
elif hp1 is not None and c1 == self.player2:
c2[0].actual_hp=hp1
c1[0].actual_hp=hp2
c2[0].actual_hp -= damage
#print(f"{c2[2]}の {c2[0]} が{damage}をうけた")
print(f"{c2[0].name_ja} が{damage}をうけた")
print("❤️",c2[0].name_ja,"残りHP",c2[0].actual_hp)
if c2[0].actual_hp > 0:
print(f"{c2[0].name_ja}技{c2[1].name_ja}を使った!")
damage = calculate_damage(c2[0], c1[0], c2[1])
took_damage2=damage
c1[0].actual_hp -= damage
print(f"{c1[0].name_ja}が{damage}を受けた")
print("⭐️",c1[0].name_ja,"残りHP",c1[0].actual_hp)
if c1 == self.player1:
return ((0,action1,took_damage1,c1[0].actual_hp),(1,action2,took_damage2,c2[0].actual_hp))
else:
return ((0,action2,took_damage2,c2[0].actual_hp),(1,action1,took_damage1,c1[0].actual_hp))
def get_winner(self):
if is_dead(self.player1):
return self.player2
if is_dead(self.player2):
return self.player1
def validate(self):
for pokemons in (self.player1,self.player2):
if len([p for p in pokemons if len(p.actual_moves) == 0]) > 0:
raise ValueError("Pokemon must have at least one move")
def run(self):
self.validate()
while True:
self.forward_step()
winner = self.get_winner()
if winner is not None:
print(f"{winner} won the battle!")
return winner
if self.turn > 500:
raise Exception("Battle is too long")
def run1(self,hp1=None,hp2=None):
self.validate()
action=self.forward_step(self,hp1=hp1,hp2=hp2)
winner = self.get_winner()
if action is not None:
reward = 0
if winner == self.player1:
print("優勝はlearner")
reward = 1
return reward
elif winner == self.player2:
print("優勝はopponent")
reward = -1
return reward
elif battle.turn > 500:
print("ターンが長い")
reward = -0.1
return reward
else:
print("バトル中")
>for child_node in self.child_nodes:
>の部分
そこが 2 回回っているという確実なデータは出されていないように見えますが。
self.turn は初期値 0 ですから、唯一 +1 しているそのループを2回 *通れば* 2 になるのは確かです。しかしループ自体が 2 回回らなくても、同じオブジェクトの next_child_node が二回呼ばれるなら、それそれループが 1 回でも self.turn が 2 になるでしょう。
121 行から 130 行の print のログが 2 つ出ていますが、 self.child_nodes の object at の値が同じなのは間接的に同じ self の next_child_node が呼ばれていることを示して、 ログの 1 つ目の self.turn が 1 で 2 つ目のが 2 であるなら 該当 for はそれぞれ 1 回ずつ回っている・・・とも考えられると思います。
確実に 2 回回っているという証拠のため、 for 内でループ毎に何かユニークな表示をしてその表示行数=ループ回数として確認するとか、コメントになっている 114 行目を復活させてみては如何でしょうか。
(コメント削除)
#を外して実行しました。エラーメッセージです
WARNING:tensorflow:No training configuration found in the save file, so the model was *not* compiled. Compile it manually.
1/1 [==============================] - 0s 106ms/step
battle実行されました
0
0
モンテカルロ 6
c1 (Jolteon(271), BodySlam, [Jolteon(271)])
サンダース が技のしかかりをつかった!
こうかはいまひとつ... 0.5
サイドン が19をうけた
❤️ サイドン 残りHP 332
サイドン技じしんを使った!
こうかはばつぐんだ! 2
サンダースが271を受けた
⭐️ サンダース 残りHP 0
前 child_nodes 1
argmax 0
turn 1
len(pucb_values) 1
pucb_values [array([0., 0., 0., 0.], dtype=float32)]
index <class 'numpy.int64'>
index 0
len(self.child_nodes) 1
self.child_nodes [<__main__.pv_mcts_scores.<locals>.Node object at 0x169bbe490>]
前 child_nodes 1
argmax 2
turn 2
len(pucb_values) 1
pucb_values [array([1. , 1. , 1.5, 1. ], dtype=float32)]
index <class 'numpy.int64'>
index 2
len(self.child_nodes) 1
self.child_nodes [<__main__.pv_mcts_scores.<locals>.Node object at 0x169bbe490>]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Cell In[23], line 44
42 c2hp=player1[0].actual_hp
43 result=((c1,-1,-1,c1hp),(c2,-1,-1,c2hp))
---> 44 next_action=action1(result)
45 winner = battle.get_winner()
46 #ゲーム終了時
Cell In[21], line 116, in pv_mcts_action.<locals>.pv_mcts_action(state)
115 def pv_mcts_action(state):
--> 116 scores = pv_mcts_scores(model, state, temperature,winner)
117 rng=np.random.default_rng()
118 return rng.choice([0,1,2,3], p=scores)
Cell In[21], line 101, in pv_mcts_scores(model, state, temperature, winner)
99 # 複数回の評価の実行
100 for _ in range(PV_EVALUATE_COUNT):
--> 101 root_node.evaluate()
103 # 合法手の確率分布
104 scores = nodes_to_scores(root_node.child_nodes)
Cell In[21], line 64, in pv_mcts_scores.<locals>.Node.evaluate(self)
59 return value
61 # 子ノードが存在する時
62 else:
63 # アーク評価値が最大の子ノードの評価で価値を取得
---> 64 value = self.next_child_node().evaluate()
66 # 累計価値と試行回数の更新
67 self.w += value
Cell In[21], line 94, in pv_mcts_scores.<locals>.Node.next_child_node(self)
92 print("len(self.child_nodes)",len(self.child_nodes))
93 print("self.child_nodes",self.child_nodes)
---> 94 return self.child_nodes[a]
IndexError: list index out of range
ノードの長さが1なのに2番目を選択しているのでエラーが発生しているのはわかっています。next_child_nodeは1回しか実行されていないように感じるのですが、どうでしょうか?
next_child_nodeが2回実行されているみたいです。if文は本の通りなのですがなぜでしょうか?if not self.child_nodes:のところです。
質問にあるエラーメッセージから、決着がついたのにループが終わらないことを問題視していると思ったのですが、コメントのやり取りを見るとそうではないようなので、過去のコメントは消しました。
ループについてはよくわかりませんが、エラーが起こっている原因は np.argmax の使い方だと思います。np.argmax(pucb_values) で、pucb_values には ndarray が入っているようなので、argmax は全体を flatten したものに対して最大になるindexを返しています。
(そこの部分でどういうことをやろうとしているのか私には理解できていないため、修正方法は提示できません)
pucb_values の中身が numpy.ndarray のリストになっていますので、
> pucb_values [array([0., 0., 0., 0.], dtype=float32)]
以下の計算式 (-child_node.w / child_node.n ...) + C_PUCT * ... で使用されている child_node.w , child_node.n, child_node.p のいずれか、もしくは複数の値が numpy.ndarray になっているものと推測されます。
def next_child_node(self):
:
for child_node in self.child_nodes:
pucb_values.append((-child_node.w / child_node.n if child_node.n else 0.0) +
C_PUCT * child_node.p * sqrt(t) / (1 + child_node.n))
child_node.n とchild.w はスカラーの様に見えるので、child_node.p の内容を確認してみるとよいかと思います。
child_node.p は predict() からの戻り値で初期化されていますが、predict(model, state) は predict(model, self.state) かと思います。(policies と values の値も確認)
# 子ノードが存在しない時
if not self.child_nodes:
# ニューラルネットワークの推論で方策と価値を取得
policies, value = predict(model, self.state)
##policies, value = predict(model, state)
:
# 子ノードの展開
self.child_nodes = []
:
for action, policy in zip(a, policies):
:
self.child_nodes.append(Node(zyoutai, policy,winner))
predictはpv_mcts_scoresの引数stateが渡されてるはずなのでstateで正しいと思います。
間違えました。self.stateが正しいと思います。
>#を外して実行しました。エラーメッセージです
確認ありがとうございます。
>前 child_nodes 1
が 2 回出ていますから、少なくともタイトルや質問本文でお聞きになっている「for文が一回多く」回る為にエラーになっているという仮定・想像は崩れたという事ですね。
ならばまた次の仮定を得るべく調査しなければなりませんが、その際は quickquip さんが整理されたように *何が事実で何が推測なのか* はっきり分けられたほうが良いと思います。
書籍に載っているコードを写しているのでしたら、一字一句見比べて違いを探してください。「同じ *はず* です」では無く「同じです」と言い切る自信があるくらいは見比べたほうが良いでしょう。
「同じです」と言い切れたら、書籍のほうを疑って正誤表等を探してみるのが(誰かに聞くより)先でしょう。時には正誤表に(まだ)無いバグかもしれませんが、そこまで調査していれば質問の際にも『書籍から全て写したがエラーが出る、書籍の正誤表にもコードの誤りは無い』と事実だけで情報を絞って提示出来ます。
書籍に載っているコードを改造しているなら、改造点を少しずつ書籍側に戻して行って問題が発生しなくなったら直前に戻した個所が問題の発生源と仮定することが出来ます。
書籍に載っているコードとか関係無く殆どご自身で組み立てているのでしたら、どこでどう動くべきなのかの正解はご自身しか知りません。ですので、(医者が問診や血液検査等で患者の状態を調べるように)あちこちに print を入れてご自身が正解と思われる通りの動作をしているか、もしくは逆に「こうなってしまったからこうなっている」と仮定したら本当にそのような異常な動作をしているかの事実確認してください。
質問の目的が変わったので新しく質問を作成し直しました。https://teratail.com/questions/mmibtpk43c5pnq
であるならば、一旦この質問はコメント欄の経緯を纏めて回答を書いて自己解決にした方がいいのではないでしょうか……?
分かりました
回答1件
あなたの回答
tips
プレビュー