Value-Based Reinforcement Learning · 학습
실행 조건
기준 Queue 예제는 NumPy로 실행합니다. 학습에 사용하지 않은 seed=100…104에서 정책을 비교합니다.
이번에 배울 내용
작은 문제를 Table로 풀어 두면, 복잡한 함수 근사 모델을 비교할 기준을 만들 수 있습니다.
Q 갱신
Q(s,a) ← Q(s,a)+α[r+γ max Q(s′,·)−Q(s,a)]. 문제 자체가 종료되면 미래 가치는 제외합니다. 시간 제한은 별도로 해석합니다.
수집과 평가
학습에서는 탐색 행동이 필요하지만 정책 평가는 같은 조건에서 분리합니다. 방문하지 않은 상태의 Q값도 확인합니다.
풀이 예제
Queue의 …20, 행동 3개를 Q-table로 학습합니다. , , 로 50 Episode를 학습하며, Episode당 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))
Q=np.zeros((21,3));visits=np.zeros((21,3),dtype=int);history=[]
rng=np.random.default_rng(7)
for episode in range(50):
env=Queue();q=env.reset(episode);total=0
for k in range(100):
a=int(rng.integers(3)) if rng.random()<.2 else int(Q[q].argmax())
nq,r,te,tr,_=env.step(a)
target=r+.95*(not te)*Q[nq].max()
Q[q,a]+=.1*(target-Q[q,a]);visits[q,a]+=1;q=nq;total+=r
if te or tr:break
history.append(total)
print(evaluate(lambda q:int(Q[q].argmax())).mean(0))
constant [-921.2 8.052 4. 3.6 ] threshold [-387.4 2.77 5.52 0. ] [-416.6 2.758 7.04 0. ]