|
协助志哥部署前端事宜,目前采取的策略为前后端运行在a800上,将徐志的工位电脑作为一个代理转发节点(因为a800没法下载atrust,因此不能直接在a800上访问化物所的服务器)。从而实现部署
强化学习:
Q-Learning
一次行动包括:当前瞬时奖励,以及记忆经验奖励
当前瞬时奖励指的是完成这一个动作直接就可获得的奖励分数,记忆经验奖励指的是按照过往经验,上一个动作发生后怎么做能取得最大奖励。
Q(si,ai)=r(si,ai)+λ∗maxa′i(Q(s′i,a′i))
e.g. 一个迷宫游戏
初始化Q和R表,Q表初始为空,R由自己定
不断迭代填充Q表,每一次来一个状态从中选取Q值最大的动作即可
代码:
import numpy as np from regex import B # 初始化参数 alpha = 0.1 # 学习率 gamma = 0.9 # 折扣因子 epsilon = 0.1 # 探索率 num_episodes = 10000 # 训练的回合数 # 你提供的 Q 表和奖励表 Q = np.zeros((6, 6)) # 6x6 Q-table,初始化为0 R = np.array([ [-1, -1, -1, -1, 0, -1], [-1, -1, -1, 0, -1, 100], [-1, -1, -1, 0, -1, -1], [-1, 0, 0, -1, 0, -1], [0, -1, -1, 0, -1, 100], [-1, 0, -1, -1, 0, 100] ]) # 选择动作的函数 def choose_action(state, epsilon): if np.random.rand() < epsilon: return np.random.choice(6) # 探索:随机选择一个动作 else: return np.argmax(Q[state, :]) # 利用:选择当前状态下价值最大的动作 # Q-learning 算法 for episode in range(num_episodes): state = np.random.randint(0, 6) # 随机选择一个初始状态 while True: while True: action = choose_action(state, epsilon) if R[state][action] != -1: break next_state = np.random.randint(0, 6) # 假设下一个状态是随机的,实际中应该是状态转移的结果 reward = R[state, action] # 获取奖励 best_next_action = np.argmax(Q[next_state, :]) # 下一个状态的最大价值动作 #===================简单更新法 Q[state, action] = reward + gamma * Q[next_state, best_next_action] # 更新Q值 #==============涉及到学习率的更新法 # Q[state, action] = (1 - alpha) * Q[state, action] + alpha * (reward + gamma * Q[next_state, best_next_action]) # 更新Q值 state = next_state # 转移到下一个状态 if state == 5: # 假设状态5是终止状态 break # 输出学习后的Q表 print("Learned Q-table:") print(Q)
DQN
由于现实场景不可能穷举所有情况,并且当前状态也可能无法使用一个表格就表达出来,因此需要引入深度学习网络替代Q
Q(si,ai)=r(si,ai)+λ∗maxa′i(Q(s′i,a′i))
对于等式左侧的Q我们定义其为eval()网络,右侧的Q定义为target()网络。target网络是记忆中的网络,因此他们结构一样,并且每迭代几次就将eval网络copy到target网络中,优化时直接使用MSE损失即可。
def choose_action(self, state) : # notation that the function return the action 's index nor the real act#EPSILON state = torch. unsqueeze(torch.FloatTensor(state) ,0) if np.random.randn() <= EPSILON: action_value = self.eval_net.forward(state) action = torch.max(action_value,1)[1].data .numpy()#找最大的那个act: action = action[0] #get the action index else: action = np.random.randint(e,NUM_ACTIONS)return action def learn(self): #learn 10e times then the target network update if self.learn_counter % Q_NETWORK_ITERATION ==0: self.target_net.load_state_dict(self.eval_net.state_dict()) self.learn_counter+=1 sample_index = np.random.choice(MEMORY_CAPACITY,BATCH_SIZE)#获取一个batch数据 batch_memory = self.memory [sample_index,: ] batch_state = torch.EloatTensor(batch_memory[:, :NUM_STATEs])#note that the action must be a int batch_action = torch.LongTensor(batch_memory[ :, NUN_STATES:NUA_STATES+1].astype(int)) batch_reward = torch.EloatTensor(batch_memory[ :, NUM_STATES+1:NUM_STATES+2]) batch_next_state = torch.EloatTensor(batch_memory[:, -NUM_STATES:]) q_eval = self.eval_net(batch_state).gather(1, batch_action)#得到当前Q(s ,a) q_next = self.target_net(batch_next_state).detach() q_target = batch_reward +GAMMA*q_next.max(1)[0].view(BATCH_SIZE,1)#公式 loss = seLf.loss(q_eval, q_target)#差异越小越好 self.optimizer.zero_grad( ) 1oss.backward( ) self.optimizer.step() net = Dqn( ) print( "The DQN is collecting experience. . . ") step_counter_list =[] for episode in range(EPISODES): state = env.reset() strp_counter = 0 while True: #====记录数据,当数据累计到一定数量开始训练模型 step_counter +=1 env.render() dction = net.choose_action(state) next_state,reward,done,info = env.step(action) reward = reward * 1 if reward >0 else reward * 5 net.store_trans(state,action,reward,next_state)#记录当前这组数据 if net.memory_counter >= MEMORY_CAPACITY:#攒够数据一起学 net.learn() if done: print( "episode {}, the reward is { }".format(episode,round(reward,3))) if done: step_counter_list.append(step_counter) net.plot(net.ax, step_counterzlist) break
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2025-5-2 11:28
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社