始める無料で始める

最小構成のDQN損失関数

select_action() 関数の準備ができたので、エージェントの学習まであと一歩です。ここでは calculate_loss() を実装します。

calculate_loss() は、エピソード中の任意のステップに対するネットワークの損失を返します。

参考までに、損失は次の式で与えられます。

この演習には次のサンプルデータが読み込まれています。

state = torch.rand(8)
next_state = torch.rand(8)
action = select_action(q_network, state)
reward = 1
gamma = .99
done = False

この演習はコースの一部です

Pythonで学ぶDeep Reinforcement Learning

コースを見る

演習の手順

  • 現在状態のQ値を取得します。
  • 次状態のQ値を取得します。
  • 目標Q値(TDターゲット)を計算します。
  • 損失関数(ベルマン誤差の二乗)を計算します。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

def calculate_loss(q_network, state, action, next_state, reward, done):
    q_values = q_network(state)
    print(f'Q-values: {q_values}')
    # Obtain the current state Q-value
    current_state_q_value = q_values[____]
    print(f'Current state Q-value: {current_state_q_value:.2f}')
    # Obtain the next state Q-value
    next_state_q_value = q_network(next_state).____    
    print(f'Next state Q-value: {next_state_q_value:.2f}')
    # Calculate the target Q-value
    target_q_value = ____ + gamma * ____ * (1-done)
    print(f'Target Q-value: {target_q_value:.2f}')
    # Obtain the loss
    loss = nn.MSELoss()(____, ____)
    print(f'Loss: {loss:.2f}')
    return loss

calculate_loss(q_network, state, action, next_state, reward, done)
コードを編集して実行