| 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 |


강화학습_오일석_12-1.png [34 KB]
프로그램 12-1 바닐라 BC로 Hopper 과업 학습.txt [3 KB]
강화학습 실습