Python(強化学習の試し01_ベースのコード)
■簡単なサンプルで強化学習について学ぶ。
入門書のネズミ学習問題は、強化学習のサンプルとして挙げられていたが、Tensorflowのライブラリなどは使っていなかった。環境から情報を得て(Observation)、それに基づき行動を決め(Action)、その結果として報酬を得る(Reward)といったことを繰り返すのが強化学習(Recurrent Learning)というものらしい。
下のようなコードを使って、強化学習を見てみたい。
ネズミ学習問題から簡素化したようなもの。
import numpy as np
class GenAction():
def getAction(self, history):
if len(history) == 0:
action = np.random.choice([0, 1])
elif history[len(history) - 1] == 0:
action = 1
else:
action = np.random.choice([0, 1])
return action
def updateSelectAction(self):
return False
def main():
num_episodes = 500
num_actions = 10
total_reward = 0
for episode in range(num_episodes):
reward = 0
history = []
ga = GenAction()
for num in range(num_actions):
action = np.random.choice([0, 1])
#action = ga.getAction(history)
if action == 0:
if num == 0:
history.append(action)
elif history[num - 1] == 0:
history.append(action)
elif history[num - 1] == 1:
history.append(action)
else:
if num == 0:
history.append(action)
elif history[num - 1] == 0:
history.append(action)
reward = reward + 1
elif history[num - 1] == 1:
history.append(action)
print(history, "Reward:" + str(reward))
total_reward = total_reward + reward
print("Average:"+str(total_reward/num_episodes))
if __name__ == '__main__':
main()
このコードは、ボタン(0と1)が2つある状態で、どちらかを押す想定。0を押した後に1を押すと報酬として1が追加される。この試行を10回繰り返す。最高では報酬5になるはず。これを1エピソードとして500エピソード繰り返すと、ランダムなら平均2.21~2.27、0の後を必ず1にすると平均3.10~3.18くらいになった。
このコードに強化学習を適用させて、この平均を上げられるか見ていきたい。