기계 학습 프레임워크 Ray - 1.4 Ray RLlib의 기본 사용

1.RLlib이란 무엇인가?

RLlib는 Ray를 기반으로 구축된 업계 수준의 강화 학습(RL) 라이브러리입니다. RLlib는 다양한 산업 및 연구 애플리케이션에 적합한 확장성이 뛰어나고 통합된 API를 제공합니다.

다음으로 Anaconda에서 Ray RLlib 환경을 생성합니다.

conda create -n RayRLlib python=3.7 
conda activate RayRLlib 
conda install pytorch==1.12.1 torchvision==0.13.1 torchaudio==0.12.1 cudatoolkit=11.3 -c pytorch
pip install tensorflow -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install tensorflow-probability -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install ipykernel -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install pyarrow
pip install gputil
pip install "ray[rllib]" -i https://pypi.tuna.tsinghua.edu.cn/simple 

위의 RayLib을 인터프리터로 선택하고 체육관 환경과 레이 라이브러리를 가져옵니다. PPO 알고리즘을 활용하여 체육관 환경을 맞춤화합니다.

import gymnasium as gym
from ray.rllib.algorithms.ppo import PPOConfig

2. 체육관과 유사한 소규모 게임 클래스 정의

SimpleCorridor라는 사용자 정의 체육관 환경이 정의됩니다. 이 환경에서 에이전트는 복도 출구에 도달하기 위해 오른쪽으로 이동하는 방법을 배워야 합니다. 에이전트는 출구에 도달하기 위해 복도로 이동해야 합니다. S는 출발점을 나타내고 G는 목표를 나타내며 복도의 길이를 구성할 수 있습니다. 에이전트가 선택할 수 있는 작업은 0(왼쪽)과 1(오른쪽)입니다. 관측값은 현재 위치의 인덱스를 나타내는 부동 소수점 숫자입니다. 목표 위치에 도달하지 않는 한(보상 값 +1.0) 각 단계의 보상 값은 -0.1입니다.

에이전트
    가 출구에 도달하기 위해 오른쪽으로 이동하는 방법을 배워야 하는 복도.

    --------
    | S | 1 | 2 | 3 | 지 | S=시작; G=골; 복도_길이=5
    --------

    선택할 수 있는 작업은 다음과 같습니다: 0=왼쪽; 1=오른쪽
    관찰은 현재 필드 인덱스를 나타내는 부동 소수점입니다(예:
    시작 위치는 0.0, 시작 위치 옆 필드는 1.0 등).
    보상은 목표(+1.0)에 도달할 때를 제외하고 모든 단계에 대해 -0.1입니다.

 클래스는 다음과 같이 정의됩니다

# Define your problem using python and Farama-Foundation's gymnasium API:

class SimpleCorridor(gym.Env):

    def __init__(self, config):
        # 初始化环境,包括设置结束位置、当前位置、动作空间(两个离散动作:左和右)和观察空间。
        self.end_pos = config["corridor_length"]
        self.cur_pos = 0
        self.action_space = gym.spaces.Discrete(2)  # left and right
        self.observation_space = gym.spaces.Box(0.0, self.end_pos, shape=(1,))

    def reset(self, *, seed=None, options=None):
        # 重置环境,将当前位置设为0,并返回初始观察值。
        """Resets the episode.

        Returns:
           Initial observation of the new episode and an info dict.
        """
        self.cur_pos = 0
        # Return initial observation.
        return [self.cur_pos], {}

    def step(self, action):
        # 根据给定的动作在环境中执行一步操作。根据动作和当前位置更新智能体位置。
        # 当到达走廊末端(目标)时,设置terminated标志。
        # 当目标达成时,奖励为+1.0,否则为-0.1。
        # 返回新的观察值、奖励、terminated标志、truncated标志和信息字典。
        
        """Takes a single step in the episode given `action`.

        Returns:
            New observation, reward, terminated-flag, truncated-flag, info-dict (empty).
        """
        # Walk left.
        if action == 0 and self.cur_pos > 0:
            self.cur_pos -= 1
        # Walk right.
        elif action == 1:
            self.cur_pos += 1
        # Set `terminated` flag when end of corridor (goal) reached.
        terminated = self.cur_pos >= self.end_pos
        truncated = False
        # +1 when goal reached, otherwise -1.
        reward = 1.0 if terminated else -0.1
        return [self.cur_pos], reward, terminated, truncated, {}

3. PPO 기반 강화학습 훈련

다음 코드는 Ray RLlib를 통해 PPOConfig 객체를 생성하고 SimpleCorridor 환경을 사용합니다. 환경 구성을 설정하고 복도 길이를 28로 설정합니다. num_rollout_workers를 10으로 설정하여 환경 탐색을 병렬화합니다. 구성을 통해 PPO 알고리즘 개체를 구성합니다.

config = (
    PPOConfig().environment(
        # Env class to use (here: our gym.Env sub-class from above).
        env=SimpleCorridor,
        # Config dict to be passed to our custom env's constructor.
        # Use corridor with 20 fields (including S and G).
        env_config={"corridor_length": 28},
    )
    # Parallelize environment rollouts.
    .rollouts(num_rollout_workers=10)
)
# Construct the actual (PPO) algorithm object from the config.
algo = config.build()

# 循环训练PPO算法20次迭代,输出每次迭代的平均奖励。
for i in range(20):
    results = algo.train()
    print(f"Iter: {i}; avg. reward={results['episode_reward_mean']}")

강화 학습 훈련은 위의 코드를 통해 10개의 병렬 롤아웃 작업자와 20개의 훈련 반복으로 수행됩니다.

훈련 중 평균 Reward 출력은 다음과 같습니다.

(RolloutWorker pid=334231) /home/yaoyao/anaconda3/envs/RayRLlib/lib/python3.7/site-packages/gymnasium/spaces/box.py:227: UserWarning: WARN: Casting input x to numpy array.
...
Iter: 0; avg. reward=-24.700000000000117
Iter: 1; avg. reward=-29.840909090909282
...
Iter: 18; avg. reward=-1.7286713286713296
Iter: 19; avg. reward=-1.7269503546099298

4. 모델 검증

복도 환경에서 전체 에피소드를 실행하세요. 초기 관찰부터 시작하여 알고리즘을 사용하여 행동을 계산하고, 행동을 환경에 적용하고, 새로운 관찰, 보상, 종료 플래그 및 잘린 플래그를 얻습니다. 보상을 누적하고 루프가 끝나면 총 보상을 출력합니다.

# 在训练完成后,使用训练好的算法在新的走廊环境(长度为10)中进行推理
env = SimpleCorridor({"corridor_length": 10})
# 首先初始化环境并获得初始观察值。
terminated = truncated = False
total_reward = 0.0
# 玩1个回合
while not terminated and not truncated:
    # Compute a single action, given the current observation
    # from the environment.
    action = algo.compute_single_action(obs)
    # Apply the computed action in the environment.
    obs, reward, terminated, truncated, info = env.step(action)
    # Sum up rewards for reporting purposes.
    total_reward += reward
# 结果输出
print(f"Played 1 episode; total-reward={total_reward}")

훈련 후 얻은 모델은 지정된 환경에서 검증되었으며 최종 보상은 +0.1로 초기 -24에 비해 크게 개선되었습니다.

Played 1 episode; total-reward=0.10000000000000009

이 경우 복도의 길이는 10이므로 Agent는 최적의 전략(항상 오른쪽으로 걷는다)을 취하고, 얻을 수 있는 최대 보상은 다음과 같다.Rmax=9\times \left ( -0.1 \right )+\left ( +1 \right )=+0.1

Agent가 PPO 알고리즘을 통해 최적의 전략을 학습했음을 알 수 있습니다.

추천

출처blog.csdn.net/wenquantongxin/article/details/129969925