정성훈
    프로그램 12-1) 바닐라 BC로 Hopper 과업 학습
강화학습_오일석_12-1.png [34 KB]   프로그램 12-1 바닐라 BC로 Hopper 과업 학습.txt [3 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
import gymnasium as gym
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam
 
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
 
activation = tf.keras.activations.tanh
initializer = tf.keras.initializers.Orthogonal
 
def expert_surrogator():  # [프로그램 10-1]의 정책 신경망이 expert를 대행
    actor = ActorNetwork()
    actor.build((None, s_dim)) # Explicitly build the model before loading weights
    actor.load_weights('f10-1.weights.h5')
    return actor
 
def mlp_network():  # BC가 학습할 신경망(MLP) 구축
    nn = Sequential()
    nn.add(Dense(64, input_shape=(s_dim,)))
    nn.add(Dense(64))
    nn.add(Dense(a_dim))
    return nn
 
def demonstration_data_by_expert(expert_policy, n_traj=300):  # expert로 시연 데이터 수집
    demo_data = []
    for i in range(n_traj):
        traj = []
        s, info = env.reset()
        while True:
            mean = expert_policy(s.reshape(1, -1))
            action = mean[0]
            s1, r, terminated, truncated, info = env.step(action)
            traj.append([s, action])
            s = s1
 
            if terminated or truncated:
                if (i+1) % 20 == 0:
                    print('시연 데이터의', i+1, '번째 궤적 길이=', len(traj))
                demo_data.append(traj)
                break
    return demo_data
 
env = gym.make('Hopper-v4', render_mode='rgb_array')
s_dim = env.observation_space.shape[0]
a_dim = env.action_space.shape[0]
 
expert = expert_surrogator()        # expert를 대행할 신경망
policy_bc_vanilla = mlp_network()   # BC가 학습할 신경망
 
D = demonstration_data_by_expert(expert)  # 시연 데이터 수집
 
# Fix: Flatten the list of trajectories into individual states and actions
all_states = []
all_actions = []
for traj in D:
    for s, action in traj:
        all_states.append(s)
        all_actions.append(action)
 
X = np.array(all_states)
Y = np.array(all_actions)
 
policy_bc_vanilla.compile(loss='MSE', optimizer=Adam())
policy_bc_vanilla.fit(X, Y, batch_size=128, epochs=100, verbose=1)  # 정책 신경망 학습
 
policy_bc_vanilla.save('f12-1.keras')  # 신경망 저장
env.close()
cs

  등록일 : 2025-11-30 [16:54] 조회 : 139 다운 : 168   
 
△ 이전글12장) 흉내 학습 (Imitation Learning)
▽ 다음글10장) 신뢰 영역 (Trust Region) 방법
강화학습 실습
번호 ⓒ 제 목 이름
강화학습 - 기초 개념부터 최신 알고리즘까지 이론과 실습을 통해 응용으로...
바닥부터 배우는 강화 학습 코드 (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]