공개 환경과 실험 기록 · 학습
실행 조건
기준 Queue 예제는 NumPy로 실행합니다. 학습에 사용하지 않은 seed=100…104에서 정책을 비교합니다.
공개 환경 활동은 gymnasium·stable-baselines3를 사용합니다. 시각화할 때만 gymnasium[classic-control]이 필요합니다.
필요한 패키지가 없으면 Colab·Jupyter 코드 셀에서 %pip install control==0.10.2 gymnasium==1.3.0 stable-baselines3==2.9.2를 실행하세요.
이번에 배울 내용
종료 처리 한 줄이 학습 Target을 바꿀 수 있습니다. 환경 경계와 공정한 정책 평가부터 확인합니다.
전체 흐름
환경·관측 → 정책·행동 → Transition·보상 → 공통 조건의 평가
상호작용의 단위
reset은 초기 관측과 info를, step은 새 관측·보상·terminated·truncated·info를 돌려줍니다. 실제 종료와 수집 시간 제한을 구분해야 학습 Target을 올바르게 계산할 수 있습니다.
재사용할 Transition
관측·행동·보상·다음 관측·종료 유형을 함께 저장합니다. Episode 경계와 환경 ID·seed가 있어야 Transition의 의미를 다시 읽을 수 있습니다.
풀이 예제
Queue 예제로 reset→step→종료의 흐름을 실행합니다. seed=7, 행동 1(용량 2), 100 step입니다.
"""Synthetic service queue. An action chooses capacity, including its energy cost."""
import numpy as np
class Queue:
def reset(self, seed=0):
self.rng = np.random.default_rng(seed)
self.q, self.t = 0, 0
return self.q
def step(self, action):
capacity = (0, 2, 4)[int(action)]
arriving = int(self.rng.poisson(2))
raw = max(0, self.q - capacity) + arriving
dropped = max(0, raw - 20)
self.q = min(20, raw)
self.t += 1
reward = -(self.q + .2 * capacity**2 + 10 * dropped)
return self.q, reward, False, self.t >= 100, {'queue': self.q, 'capacity': capacity, 'dropped': dropped}
def evaluate(policy, seeds=range(100, 105)):
rows = []
for seed in seeds:
env = Queue(); q = env.reset(seed)
total = waiting = energy = dropped = 0
while True:
q, r, terminated, truncated, info = env.step(policy(q))
total += r; waiting += q; energy += info['capacity']**2; dropped += info['dropped']
if terminated or truncated: break
rows.append([total, waiting / env.t, energy / env.t, dropped])
return np.array(rows)
policies = {'constant': lambda q: 1, 'threshold': lambda q: 0 if q == 0 else (1 if q < 5 else 2)}
for name, policy in policies.items():
print(name, evaluate(policy).mean(axis=0))
env=Queue();q=env.reset(7)
for k in range(5):
nq,r,te,tr,info=env.step(1);print(k,q,1,r,nq,te,tr);q=nq
constant [-921.2 8.052 4. 3.6 ] threshold [-387.4 2.77 5.52 0. ] 0 0 1 -3.8 3 False False 1 3 1 -3.8 3 False False 2 3 1 -4.8 4 False False 3 4 1 -3.8 3 False False 4 3 1 -3.8 3 False False