

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# 報酬関数のカスタマイズ
<a name="reward-function"></a>

報酬関数の作成は、インセンティブプランを設計するのに似ています。パラメータは、インセンティブプランの作成に使用できる値です。

インセンティブ戦略が異なると、車両の動作も異なります。車両が速く走るようにするには、ラップの終了に時間がかかりすぎたり、トラックから外れた際に負の値を付けてください。ジグザグな運転パターンを避けるために、ステアリング角度の範囲制限を定義して、トラックのまっすぐなセクションで積極的にステアリングを使用しない車両に報酬を与えるようにしてください。

トラックの中心線およびトラックの外側と内側のエッジに沿って配置された番号付きの指標であるウェイポイントを使用して、直線や曲線などのトラックの特徴と特定の運転動作を関連付けることができます。

効果的な報酬関数の作成は、クリエイティブで反復的なプロセスです。さまざまな戦略を試し、パラメータをミックスして一致させ、そして何より、楽しんでください。

**Topics**
+ [Python コードを編集して報酬関数をカスタマイズする](#edit-reward-function)
+ [AWS DeepRacer 報酬関数の入力パラメータ](#deepracer-reward-function-input)

## Python コードを編集して報酬関数をカスタマイズする
<a name="edit-reward-function"></a>

In AWS DeepRacer Student では、サンプル報酬関数を編集して、モデルのカスタムレース戦略を作成できます。

**報酬機能をカスタマイズする方法**

1.  AWS DeepRacer Student **Create モデル**エクスペリエンスの**ステップ 5: 報酬関数をカスタマイズ**するページで、サンプル報酬関数を選択します。

1. Python コードを使用して報酬関数の入力パラメータをカスタマイズするには、サンプルの報酬関数ピッカーの下にあるコードエディタを使用します。

1. **[Validate]** (検証)を選択して、コードが動作するかどうかをチェックします。または、**[Reset]** (リセット) を選択してやり直してください。

1. 変更が完了したら、**[Next]** (次へ) を選択します。

[AWS DeepRacer 報酬関数の入力パラメータ](#deepracer-reward-function-input) を参照して、各パラメータを確認してください。報酬関数の例で、さまざまなパラメータがどのように使われているかを確認してください。

## AWS DeepRacer 報酬関数の入力パラメータ
<a name="deepracer-reward-function-input"></a>

 AWS DeepRacer 報酬関数は、変数 として渡されたディクショナリオブジェクトを入力`params`として受け取ります。

```
def reward_function(params) :

    reward = ...

    return float(reward)
```

`params` 辞書オブジェクトには、次のキーと値のペアが含まれています。

```
{
    "all_wheels_on_track": Boolean,        # flag to indicate if the agent is on the track
    "x": float,                            # agent's x-coordinate in meters
    "y": float,                            # agent's y-coordinate in meters
    "closest_objects": [int, int],         # zero-based indices of the two closest objects to the agent's current position of (x, y).
    "closest_waypoints": [int, int],       # indices of the two nearest waypoints.
    "distance_from_center": float,         # distance in meters from the track center
    "is_crashed": Boolean,                 # Boolean flag to indicate whether the agent has crashed.
    "is_left_of_center": Boolean,          # Flag to indicate if the agent is on the left side to the track center or not.
    "is_offtrack": Boolean,                # Boolean flag to indicate whether the agent has gone off track.
    "is_reversed": Boolean,                # flag to indicate if the agent is driving clockwise (True) or counter clockwise (False).
    "heading": float,                      # agent's yaw in degrees
    "objects_distance": [float, ],         # list of the objects' distances in meters between 0 and track_length in relation to the starting line.
    "objects_heading": [float, ],          # list of the objects' headings in degrees between -180 and 180.
    "objects_left_of_center": [Boolean, ], # list of Boolean flags indicating whether elements' objects are left of the center (True) or not (False).
    "objects_location": [(float, float),], # list of object locations [(x,y), ...].
    "objects_speed": [float, ],            # list of the objects' speeds in meters per second.
    "progress": float,                     # percentage of track completed
    "speed": float,                        # agent's speed in meters per second (m/s)
    "steering_angle": float,               # agent's steering angle in degrees
    "steps": int,                          # number steps completed
    "track_length": float,                 # track length in meters.
    "track_width": float,                  # width of the track
    "waypoints": [(float, float), ]        # list of (x,y) as milestones along the track center

}
```

次のリファレンスを使用して、 AWS DeepRacer 入力パラメータをよりよく理解します。

### all\$1wheels\$1on\$1track
<a name="reward-function-input-all_wheels_on_track"></a>

**タイプ: ** `Boolean`

**範囲: ** `(True:False)`

エージェントがトラック上にあるか否かを示す `Boolean` フラグ。車輪のいずれかがトラックの境界線の外側にある場合、エージェントはトラック上にありません (`False`)。4 つの車輪すべてがトラックの境界の内側にある場合、トラック上にあります (`True`)。次のイラストレーションは、エージェントがトラック上にあることを示しています。

![\[\]](http://docs.aws.amazon.com/ja_jp/deepracer/latest/student-userguide/images/reward-function/deepracer-reward-function-input-all_wheels_on_track-true.png)


次のイラストレーションでは、2 つの車輪がトラックの境界の外側にあるため、エージェントはトラック上にありません。

![\[\]](http://docs.aws.amazon.com/ja_jp/deepracer/latest/student-userguide/images/reward-function/deepracer-reward-function-input-all_wheels_on_track-false.png)


**例: ** *`all_wheels_on_track` パラメータを試用した報酬関数*

```
def reward_function(params):
    #############################################################################
    '''
    Example of using all_wheels_on_track and speed
    '''

    # Read input variables
    all_wheels_on_track = params['all_wheels_on_track']
    speed = params['speed']

    # Set the speed threshold based your action space
    SPEED_THRESHOLD = 1.0

    if not all_wheels_on_track:
        # Penalize if the car goes off track
        reward = 1e-3
    elif speed < SPEED_THRESHOLD:
        # Penalize if the car goes too slow
        reward = 0.5
    else:
        # High reward if the car stays on track and goes fast
        reward = 1.0

    return float(reward)
```

### closest\$1waypoints
<a name="reward-function-input-closest_waypoints"></a>

**タイプ**: `[int, int]`

**範囲**: `[(0:Max-1),(1:Max-1)]`

`(x, y)` のエージェントの現在位置に最も近い 2 つが隣接する `waypoint` のゼロベースのインデックス。距離は、エージェントの中心からのユークリッド距離によって測定されます。最初の要素は、エージェントの背後に最も近いウェイポイントを指し、2 番目の要素は、エージェントの前面にある最も近いウェイポイントを指します。`Max` は、ウェイポイントリストの長さです。[ウェイポイント](#reward-function-input-waypoints) で示しているイラストレーションでは、`closest_waypoints` は `[16, 17]` になります。

次の例の報酬関数は、`waypoints` と`closest_waypoints`、および `heading` を使用して即時報酬を計算する方法を示しています。

AWS DeepRacer は、、`math`、、`random``numpy`、 `scipy`の Python ライブラリをサポートしています`shapely`。これらの 1 つを使用するには、関数定義 `import supported library` の前に、インポートステートメント `def reward_function(params)` を追加します。

**例**: *`closest_waypoints` パラメータを使用する報酬関数*

```
# Place import statement outside of function (supported libraries: math, random, numpy, scipy, and shapely)
# Example imports of available libraries
#
# import math
# import random
# import numpy
# import scipy
# import shapely

import math

def reward_function(params):
    ###############################################################################
    '''
    Example of using waypoints and heading to make the car point in the right direction
    '''

    # Read input variables
    waypoints = params['waypoints']
    closest_waypoints = params['closest_waypoints']
    heading = params['heading']

    # Initialize the reward with typical value
    reward = 1.0

    # Calculate the direction of the centerline based on the closest waypoints
    next_point = waypoints[closest_waypoints[1]]
    prev_point = waypoints[closest_waypoints[0]]

    # Calculate the direction in radius, arctan2(dy, dx), the result is (-pi, pi) in radians
    track_direction = math.atan2(next_point[1] - prev_point[1], next_point[0] - prev_point[0])
    # Convert to degree
    track_direction = math.degrees(track_direction)

    # Calculate the difference between the track direction and the heading direction of the car
    direction_diff = abs(track_direction - heading)
    if direction_diff > 180:
        direction_diff = 360 - direction_diff

    # Penalize the reward if the difference is too large
    DIRECTION_THRESHOLD = 10.0
    if direction_diff > DIRECTION_THRESHOLD:
        reward *= 0.5

    return float(reward)
​
```

### closest\$1objects
<a name="reward-function-input-closest_objects"></a>

**タイプ**: `[int, int]`

**範囲**: `[(0:len(object_locations)-1), (0:len(object_locations)-1]`

エージェントの現在の位置（x、y）に最も近い 2 つのオブジェクトのゼロから始まるインデックス。最初のインデックスは、エージェントの背後にある最も近いオブジェクトを参照し、2 番目のインデックスは、エージェントの前にある最も近いオブジェクトを参照します。オブジェクトが 1 つしかない場合、両方のインデックスは 0 です。

### distance\$1from\$1center
<a name="reward-function-input-distance_from_center"></a>

**タイプ**: `float`

**範囲**: `0:~track_width/2`

エージェントの中心とトラックの中心との間の変位 (メートル単位)。観察可能な最大変位は、エージェントのいずれかの車輪がトラックの境界線の外側にあるときに発生し、トラックの境界線の幅に応じて、`track_width` の半分よりわずかに小さいまたは大きい場合があります。

![\[\]](http://docs.aws.amazon.com/ja_jp/deepracer/latest/student-userguide/images/reward-function/deepracer-reward-function-input-distance_from_center.png)


**例:** *`distance_from_center` パラメータを使用する報酬関数*

```
def reward_function(params):
    #################################################################################
    '''
    Example of using distance from the center
    '''

    # Read input variable
    track_width = params['track_width']
    distance_from_center = params['distance_from_center']

    # Penalize if the car is too far away from the center
    marker_1 = 0.1 * track_width
    marker_2 = 0.5 * track_width

    if distance_from_center <= marker_1:
        reward = 1.0
    elif distance_from_center <= marker_2:
        reward = 0.5
    else:
        reward = 1e-3  # likely crashed/ close to off track

    return float(reward)
```

### heading
<a name="reward-function-input-heading"></a>

**タイプ**: `float`

**範囲**: `-180:+180`

座標の x 軸に対するエージェントの進行方向 (度単位)。

![\[\]](http://docs.aws.amazon.com/ja_jp/deepracer/latest/student-userguide/images/reward-function/deepracer-reward-function-input-heading.png)


**例:** *`heading` パラメータを使用する報酬関数*

詳細については、「[`closest_waypoints`](#reward-function-input-closest_waypoints)」を参照してください。

### is\$1crashed
<a name="reward-function-input-crashed"></a>

**タイプ**: `Boolean`

**範囲**: `(True:False)`

エージェントが終了ステータスとして別のオブジェクトにクラッシュしたか (`True`) 否か (`False`) を示す `Boolean` フラグ。

### is\$1left\$1of\$1center
<a name="reward-function-input-is_left_of_center"></a>

**タイプ**: `Boolean`

**範囲**: `[True : False]`

エージェントがトラックの中心から左にあるか (`True`) 否か (`False`) を示す `Boolean` フラグ。

### is\$1offtrack
<a name="reward-function-input-offtrack"></a>

**タイプ**: `Boolean`

**範囲**: `(True:False)`

エージェントの 4 つの車輪すべてがトラックの内側または外側の境界線の外を走っているか (`True`) 否か (`False`) を示す `Boolean` フラグ。

### is\$1reversed
<a name="reward-function-input-is_reversed"></a>

**タイプ**: `Boolean`

**範囲**: `[True:False]`

エージェントが時計回り (`True`) であるか反時計回り (`False`) のどちらで運転しているかを示す `Boolean` フラグ。

これは、エピソードごとに方向変更を有効にする場合に使用されます。

### objects\$1distance
<a name="reward-function-input-objects_distance"></a>

**タイプ**: `[float, … ]`

**範囲**: `[(0:track_length), … ]`

開始線に対する環境内のオブジェクト間の距離のリスト。i 番目の要素は、i 番目のオブジェクトと、トラックの中心線に沿った開始線間の距離をメートルで測定します。

**注記**  
abs \$1 (var1) - (var2)\$1 = how close the car is to an object, WHEN var1 = ["objects\$1distance"][index] and var2 = params["progress"]\$1params["track\$1length"]  
車両の前面に最も近いオブジェクトと車両の背後に最も近いオブジェクトのインデックスを取得するには、`closest_objects` パラメータを使用します。

### objects\$1heading
<a name="reward-function-input-objects_heading"></a>

**タイプ**: `[float, … ]`

**範囲**: `[(-180:180), … ]`

オブジェクトの見出しのリスト（度単位）。i番目の 要素は、i番目の オブジェクトの見出しを測定します。静止オブジェクトの見出しは 0 です。ボットカーの場合、対応する要素の値はその車両の見出しの角度です。

### objects\$1left\$1of\$1center
<a name="reward-function-input-objects_left_of_center"></a>

**タイプ**: `[Boolean, … ]`

**範囲**: `[True|False, … ]`

`Boolean` フラグのリスト。i 番目の要素の値は、i 番目のオブジェクトがトラックの中心から左側 (`True`) か右側 (`False`) かを示します。

### objects\$1location
<a name="reward-function-input-objects_location"></a>

**タイプ**: `[(x,y), ...]`

**範囲**: `[(0:N,0:N), ...]`

このパラメータには、すべてのオブジェクトの位置が格納されます。それぞれの位置は ([x、y](#reward-function-input-x_y)) のタプルです。

リストのサイズは、トラック上のオブジェクトの数と同じです。リストされるオブジェクトには、静止オブジェクトと動いているボットカーの両方が含まれます。

### objects\$1speed
<a name="reward-function-input-objects_speed"></a>

**タイプ**: `[float, … ]`

**範囲**: `[(0:12.0), … ]`

トラック上のオブジェクトの速度（メートル/秒）のリスト。静止オブジェクトの場合、速度は 0 です。ボット車両の場合、値はトレーニングで設定した速度です。

### プログレス
<a name="reward-function-input-progress"></a>

**タイプ**: `float`

**範囲**: `0:100`

トラック完走の割合。

**例:** *`progress` パラメータを使用する報酬関数*

詳細については、「[ステップ](#reward-function-input-steps)」を参照してください。

### speed
<a name="reward-function-input-speed"></a>

**タイプ**: `float`

**範囲**: `0.0:5.0`

エージェントの観測速度（メートル/秒）。

![\[\]](http://docs.aws.amazon.com/ja_jp/deepracer/latest/student-userguide/images/reward-function/deepracer-reward-function-input-speed.png)


**例:** *`speed` パラメータを使用する報酬関数*

詳細については、「[all\$1wheels\$1on\$1track](#reward-function-input-all_wheels_on_track)」を参照してください。

### steering\$1angle
<a name="reward-function-input-steering_angle"></a>

**タイプ**: `float`

**範囲**: `-30:30`

エージェントの中心線からの前輪のステアリング角（度単位）。負の記号 (-) は右へのステアリングを意味し、正の (\$1) 記号は左へのステアリングを意味します。次の図に示すように、エージェントの中心線はトラックの中心線と必ずしも平行ではありません。

![\[\]](http://docs.aws.amazon.com/ja_jp/deepracer/latest/student-userguide/images/reward-function/deepracer-reward-function-steering.png)


**例:** *`steering_angle` パラメータを使用する報酬関数*

```
def reward_function(params):
    '''
    Example of using steering angle
    '''

    # Read input variable
    abs_steering = abs(params['steering_angle']) # We don't care whether it is left or right steering

    # Initialize the reward with typical value
    reward = 1.0

    # Penalize if car steer too much to prevent zigzag
    ABS_STEERING_THRESHOLD = 20.0
    if abs_steering > ABS_STEERING_THRESHOLD:
        reward *= 0.8

    return float(reward)
```

### ステップ
<a name="reward-function-input-steps"></a>

**タイプ**: `int`

**範囲**: `0:Nstep`

完了した手順の数。手順は、現在のポリシーを使用してエージェントが行う観察アクションのシーケンスに対応します。

**例:** *`steps` パラメータを使用する報酬関数*

```
def reward_function(params):
    #############################################################################
    '''
    Example of using steps and progress
    '''

    # Read input variable
    steps = params['steps']
    progress = params['progress']

    # Total num of steps we want the car to finish the lap, it will vary depends on the track length
    TOTAL_NUM_STEPS = 300

    # Initialize the reward with typical value
    reward = 1.0

    # Give additional reward if the car pass every 100 steps faster than expected
    if (steps % 100) == 0 and progress > (steps / TOTAL_NUM_STEPS) * 100 :
        reward += 10.0

    return float(reward)
```

### track\$1length
<a name="reward-function-input-track_len"></a>

**タイプ**: `float`

**範囲**: `[0:Lmax]`

トラックの長さ（メートル単位）。`Lmax is track-dependent.`

### track\$1width
<a name="reward-function-input-track_width"></a>

**タイプ**: `float`

**範囲**: `0:Dtrack`

トラックの幅 (メートル)。

![\[\]](http://docs.aws.amazon.com/ja_jp/deepracer/latest/student-userguide/images/reward-function/deepracer-reward-function-input-track_width.png)


**例:** *`track_width` パラメータを使用する報酬関数*

```
def reward_function(params):
    #############################################################################
    '''
    Example of using track width
    '''

    # Read input variable
    track_width = params['track_width']
    distance_from_center = params['distance_from_center']

    # Calculate the distance from each border
    distance_from_border = 0.5 * track_width - distance_from_center

    # Reward higher if the car stays inside the track borders
    if distance_from_border >= 0.05:
        reward = 1.0
    else:
        reward = 1e-3 # Low reward if too close to the border or goes off the track

    return float(reward)
```

### x、y
<a name="reward-function-input-x_y"></a>

**タイプ**: `float`

**範囲**: `0:N`

トラックを含むシミュレーション環境における x 軸および y 軸上のエージェントの中心の位置 (メートル単位)。原点は、シミュレーション環境の左下隅にあります。

![\[\]](http://docs.aws.amazon.com/ja_jp/deepracer/latest/student-userguide/images/reward-function/deepracer-reward-function-input-x-y.png)


### ウェイポイント
<a name="reward-function-input-waypoints"></a>

**タイプ**: `[float, float]` の `list`

**範囲**: `[[xw,0,yw,0] … [xw,Max-1, yw,Max-1]]`

トラックの中心に沿ったトラック依存 `Max` マイルストーンの順序付きリスト。各マイルストーンは、(x w,i、y w,i) の座標で表されます。ループされたトラックの場合、最初と最後のウェイポイントは同じです。直線のトラックなどループされないトラックの場合、最初と最後のウェイポイントは異なります。

![\[\]](http://docs.aws.amazon.com/ja_jp/deepracer/latest/student-userguide/images/reward-function/deepracer-reward-function-input-waypoints.png)


**例** *`waypoints` パラメータを使用する報酬関数*

詳細については、「[`closest_waypoints`](#reward-function-input-closest_waypoints)」を参照してください。