정성훈
    프로그램 10-1) PPO-clip을 이용한 Hopper 과업 학습
강화학습_오일석_10-1.png [59 KB]   프로그램 10-1 PPO-clip을 이용한 Hopper 과업 학습.txt [9 KB]  




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import gymnasium as gym
import numpy as np
import scipy
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense
import matplotlib.pyplot as plt
import tqdm
 
def discount_cumulation(x, discount):
    return scipy.signal.lfilter([1], [1, float(-discount)], x[::-1], axis=0)[::-1]
 
class RolloutBuffer:
    def __init__(self, siz):
        self.state_mem = np.zeros((siz, s_dim), dtype=np.float32)    # 상태
        self.action_mem = np.zeros((siz, a_dim), dtype=np.float32)   # 행동
        self.advantage_mem = np.zeros(siz, dtype=np.float32)         # 이익 함수
        self.reward_mem = np.zeros(siz, dtype=np.float32)            # 보상
        self.return_mem = np.zeros(siz, dtype=np.float32)            # 이득
        self.value_mem = np.zeros(siz, dtype=np.float32)             # 가치 함수
        self.logprob_mem = np.zeros(siz, dtype=np.float32)           # 행동의 로그 확률
        self.t_start, self.t_end = 0, 0
 
    def store(self, state, action, reward, value, logprob):
        self.state_mem[self.t_end] = state
        self.action_mem[self.t_end] = action
        self.reward_mem[self.t_end] = reward
        self.value_mem[self.t_end] = value
        self.logprob_mem[self.t_end] = logprob
        self.t_end += 1
 
    def finish_trajectory(self, last_value=0):
        tslice = slice(self.t_start, self.t_end)
        rewards = np.append(self.reward_mem[tslice], last_value)
        values = np.append(self.value_mem[tslice], last_value)
 
        deltas = rewards[:-1] + gamma * values[1:] - values[:-1]
        self.advantage_mem[tslice] = discount_cumulation(deltas, gamma * lamda)  # GAE
        self.return_mem[tslice] = discount_cumulation(rewards, gamma)[:-1]       # 이득
        self.t_start = self.t_end
 
    def get(self):
        self.t_start, self.t_end = 0, 0
        if advantage_normalizing:  # 이익 정규화 적용
            mean, std = np.mean(self.advantage_mem), np.std(self.advantage_mem)
            self.advantage_mem = (self.advantage_mem - mean) / std
        return (self.state_mem,self.action_mem,self.advantage_mem,self.return_mem,self.logprob_mem)
 
class ActorNetwork(tf.keras.Model):
    def __init__(self):
        super().__init__()
        self.actor_mean=tf.keras.Sequential(
            [Input(shape=(s_dim,)),
            Dense(64,activation=activation,kernel_initializer=initializer),
            Dense(64,activation=activation,kernel_initializer=initializer),
            Dense(a_dim,kernel_initializer=initializer)])
 
    def call(self, state):
        mean = self.actor_mean(state)
        return mean
 
    def sample_action(self, state, std):  # 행동 샘플링
        mean = self.call(state)
        noise = tf.random.normal(shape=mean.shape)
        action = mean + noise * std
        return action
 
    def log_prob(self, state, action, std):  # 가우시안의 로그
        mean = self.call(state)
        log_v1 = -0.5 * tf.square((action - mean) / std)
        log_v2 = 0.5 * tf.math.log(2.0 * np.pi) + tf.math.log(std)
        return tf.reduce_sum(log_v1 - log_v2, axis=1)
 
class CriticNetwork(tf.keras.Model):
    def __init__(self):
        super().__init__()
        self.critic = tf.keras.Sequential(
            [Input(shape=(s_dim,)),
            Dense(64, activation=activation, kernel_initializer=initializer),
            Dense(64, activation=activation, kernel_initializer=initializer),
            Dense(1, kernel_initializer=initializer),])
 
    def call(self, state):
        return tf.keras.ops.squeeze(self.critic(state), axis=1)
 
@tf.function
def learn_actor(states,actions,logprobs,advantages,std):
    with tf.GradientTape() as tape:
        logprobs_new=actor.log_prob(states,actions,std)
        ratio=tf.exp(logprobs_new-logprobs)
        mins=tf.where(advantages>0,(1+clip_epsilon)*advantages,(1-clip_epsilon)*advantages)
        loss=-tf.reduce_mean(tf.minimum(ratio*advantages,mins))
        if entropy_loss_term: # 엔트로피 적용
            entropy=tf.reduce_mean(tf.math.log(std)+0.5*tf.math.log(2.0*np.pi*np.e))
            entropy_loss=0.01*entropy
            loss+=entropy_loss
        grad=tape.gradient(loss,actor.trainable_variables)
        optimizer_actor.apply_gradients(zip(grad,actor.trainable_variables))
        kl=tf.reduce_mean(logprobs-logprobs_new) # 조기 멈춤에 사용
        return kl
 
@tf.function
def learn_critic(states, returns):
    with tf.GradientTape() as tape:
        values = critic(states)
        loss = tf.reduce_mean((returns - values) ** 2)
        grad = tape.gradient(loss, critic.trainable_variables)
        optimizer_critic.apply_gradients(zip(grad, critic.trainable_variables))
 
gamma, lamda = 0.99, 0.95              # 할인율, GAE 람다
steps_per_epoch, n_epoch = 4096, 100  # 세대당 반복수, 세대 반복 횟수
actor_lr, critic_lr = 3e-4, 1e-3        # 학습률
actor_iterations, critic_iterations = 80, 80  # 학습 반복 횟수
clip_epsilon = 0.2                      # PPO clip 비율(epsilon)
target_kl = 0.01                       # 조기 멈춤 임곗값
activation = tf.keras.activations.tanh  # 활성 함수
std, std_decay, std_min = 0.6065, 0.999, 0.01  # std 스케줄링 시작값과 붕괴율
initializer = tf.keras.initializers.Orthogonal  # 가중치 초기화
advantage_normalizing = False           # 이익 정규화 여부
actor_early_stopping = False            # 조기 멈춤 여부
entropy_loss_term = False               # 엔트로피 항 여부
 
task_name = 'Hopper-v4'
env = gym.make(task_name)
s_dim = env.observation_space.shape[0]
a_dim = env.action_space.shape[0]
 
mem = RolloutBuffer(steps_per_epoch)
actor = ActorNetwork()
# Add explicit build call for the actor network
actor.build(input_shape=(None, s_dim))
critic = CriticNetwork()
critic.build(input_shape=(None, s_dim))
optimizer_actor = tf.keras.optimizers.Adam(learning_rate=actor_lr)
optimizer_critic = tf.keras.optimizers.Adam(learning_rate=critic_lr)
 
epi_lengths, epi_scores = [], []
length_per_epoch, score_per_epoch = [], []
state, info = env.reset()
for epoch in tqdm.tqdm(range(n_epoch)):
    n_epi, length, score = 0, 0, 0
    std = max(std_min, std * std_decay)  # std 스케줄링
    for t in range(steps_per_epoch):
        action = actor.sample_action(state.reshape(1, -1), std)
        logprob_t = actor.log_prob(state.reshape(1, -1), action, std)
        value_t = critic(state.reshape(1, -1))
        state_, reward, terminated, truncated, _ = env.step(action[0].numpy())
        mem.store(state,action[0],reward,value_t,logprob_t)
        state=state_
 
        score+=reward
        length+=1
 
        if (terminated or truncated) or (t == steps_per_epoch - 1):
            last_value = 0 if (terminated or truncated) else critic(state.reshape(1, -1))
            mem.finish_trajectory(last_value)
 
            if terminated or truncated:
                n_epi += 1
                epi_lengths.append(length)
                epi_scores.append(score)
 
            length, score = 0, 0
            state, info = env.reset()
 
    states, actions, advantages, returns, logprobs = mem.get()
    for k in range(actor_iterations):  # actor 학습
        kl = learn_actor(states, actions, logprobs, advantages, std)
        if actor_early_stopping and kl>1.5*target_kl: # 조기 멈춤 적용
            break
    for k in range(critic_iterations):  # critic 학습
        learn_critic(states, returns)
 
    length_per_epoch.append(np.mean(epi_lengths[-n_epi:]))
    score_per_epoch.append(np.mean(epi_scores[-n_epi:]))
    if (epoch + 1) % 10 == 0:
        print(f' 에피소드 길이(점수) {np.mean(length_per_epoch[-10:]):.2f},{np.mean(score_per_epoch[-10:]):.2f}')
 
actor.save_weights('f10-1.weights.h5')
env.close()
 
plt.figure(figsize=(16, 5))
smooth = np.convolve(score_per_epoch, 10 * [0.1], mode='valid')
plt.plot(range(1, len(smooth) + 1), smooth)
smooth = np.convolve(length_per_epoch, 10 * [0.1], mode='valid')
plt.plot(range(1, len(smooth) + 1), smooth)
plt.title('PPO scores for ' + task_name)
plt.ylabel('Length and Score)')
plt.xlabel('Epoch')
plt.legend(['Score', 'Length'])
plt.grid()
plt.show()
cs

  등록일 : 2025-11-30 [16:53] 조회 : 128 다운 : 168   
 
△ 이전글10장) 신뢰 영역 (Trust Region) 방법
▽ 다음글파이썬과 케라스로 배우는 강화학습 (github)
강화학습 실습
번호 ⓒ 제 목 이름
강화학습 - 기초 개념부터 최신 알고리즘까지 이론과 실습을 통해 응용으로...
바닥부터 배우는 강화 학습 코드 (github)
강화학습/심층강화학습 특강 (github)
파이썬과 케라스로 배우는 강화학습 (github)
31 l강화학습 - 기초 개념부터 최신 알고리즘까지 이론과 실습을 통해 응용으로 가는 길 (오일석) 정성훈
30 └❶ 12장) 흉내 학습 (Imitation Learning) 정성훈
29    └❷ 프로그램 12-1) 바닐라 BC로 Hopper 과업 학습 정성훈
28 └❶ 10장) 신뢰 영역 (Trust Region) 방법 정성훈
27    └❷ 프로그램 10-1) PPO-clip을 이용한 Hopper 과업 학습 정성훈
26 l파이썬과 케라스로 배우는 강화학습 (github) 정성훈
25 └❶ 7장) 아타리 브레이크 아웃 (A3C) 정성훈
24 └❶ 7장) 아타리 브레이크 아웃 (DQN) 정성훈
23 l강화학습/심층강화학습 특강 (github) 정성훈
22 └❶ 13장) 스네이크 게임 마스터 되기 정성훈
21 └❶ 10장) 자율주행차를 위한 AI 정성훈
20 l바닥부터 배우는 강화 학습 코드 (github) 정성훈
19 └❶ 파이썬과 케라스로 배우는 강화학습이 5장) 텐서플로 2.0과 케라스 정성훈
18    └❷ 파이썬과 케라스로 배우는 강화학습이 5장) 텐서플로 2.0과 케라스 정성훈
17 └❶ l9장) ActorCritic (ch9_ActorCritic.py) 정성훈

[1][2][3]