赞
踩
目录
利用深度强化模型的代码,改变网络结构和奖励策略,提高网络的平均得分。
调整网络结构,全连接层的参数改为16、16、16,200次迭代,gamma=0.95,结果如下:
全连接层的参数改为32、32、32,2000次迭代,gamma=0.95,结果如下:
全连接层的参数改为64、64、64,2000次迭代,gamma=0.95,结果如下:
全连接层的参数改为128、128、128,2000次迭代,gamma=0.99,结果如下:
全连接层的参数改为256、256、256,2000次迭代,gamma=0.90,结果如下:
- # 要先安装gym模块
- # pip install gym
- # pip install pyglet==1.2.4
-
- import random
- import numpy as np
- import matplotlib.pyplot as plt
- from keras.layers import Dense, Activation
- from keras.models import Sequential
- from keras import backend as K
- from collections import deque
- import gym
-
- '''
- bellman函数:
- target = reward + gamma * np.amax(model.predict(new_state)[0])
- Q(s,a) = r + gamma* max(Q(s',a'))
- 参数含义:
- s 代表当前的状态,a 代表当前状态所采取的行动,
- s’ 代表这个行动所引起的下一个状态,a’ 是这个新状态时采取的行动,
- r 代表采取这个行动所得到的奖励 reward,gamma是加权因子,
- 由公式可以看出 s,a 对的 Q 值等于 即时奖励 + 未来奖励* gamma。
- gamma决定了未来奖励的重要性有多大。
- 比如说,我们到了一个状态,它虽然离目标状态远了一些,但是却离游戏失败远了一些,
- 那这个状态的即时奖励就很小,但是未来奖励就很多。
- '''
-
- # In[0]: 小车载杆问题
- # 控制滑块左右移动,不让竖着的柱子掉下来
- # state:(位置x,x加速度, 角加速度, 偏移角度theta)
- # 小车的世界,就一条x轴,
- # 变量env.x_threshold里存放着小车坐标的最大值(=2.4),
- # 超过这个数值,世界结束
- # 每step()一次,就会奖励 1
-
- env = gym.make('CartPole-v1') #小车载杆模型
- state = env.reset()
- #env.render()
- #env.close()
-
- # In[1]:
-
- # 0或1 表示让小车向 左或右 移动
- action = 0
-
- # env.step(action)表示给环境发送命令
- new_state, reward, done , info = env.step(action)
- print((new_state, reward, done, info))
-
- new_state, reward, done , info = env.step(action)
- print((new_state, reward, done, info))
-
- new_state, reward, done , info = env.step(action)
- print((new_state, reward, done, info))
- # In[2]:
- def random_actions_game(episodes):
- for episode in range(episodes):
- env.reset()
- score = 0
- done = False
- while not done:
- #随机向环境发生命令
- action = random.choice([0, 1])
- new_state, reward, done, info = env.step(action)
- score += 1
-
- print('Episode: {} score: {}'.format(episode + 1, score))
-
- random_actions_game(10)
-
- # In[3]: 构建网络,预测当前状态下每个action的获得的奖励
-
- # states=4, actions=2
- def agent(states, actions):
- model = Sequential()
- model.add(Dense(256, input_dim = states))
- model.add(Activation('relu'))
- model.add(Dense(256))
- model.add(Activation('relu'))
- model.add(Dense(256))
- model.add(Activation('relu'))
- #网络最后输出两种结果,分别对应在当前状态下采取两种行动时所得最终回报
- model.add(Dense(actions))
- model.add(Activation('linear'))
- return model
-
- # In[4]: epsilon随机贪婪算法选择行动
-
- '''
- 根据epsilon贪婪算法,对于给定epsilon,在[0,1]内构造一个随机数,
- 如果随机数的值比epsilon小,那么我们随机在两种行动中选择一种,
- 如果比episilon大,我们让网络来决定当前状态
- '''
- def agent_action(model, epsilon, state, actions):
- if np.random.rand() <= epsilon:
- #随机在两种行动中选一种
- act = random.randrange(actions)
- else:
- act = np.argmax(model.predict(state)[0])
- return act
-
- # In[5]: 画图函数,训练结果显示
-
- def performance_plot(scores, target_score):
- scores_arr = np.array(scores)
- scores_arr[np.where(scores_arr > target_score)] = target_score
- plt.figure(figsize = (20, 5))
- plt.title('Plot of Score v/s Episode')
- plt.xlabel('Episodes')
- plt.ylabel('Scores')
- plt.plot(scores_arr)
- plt.show()
-
- # In[6]:
-
- '''
- 将状态点,行动,环境反馈,下一个状态点等信息存储在队列里,
- 输入网络,让网络识别如何在给定状态的中选择合适的行动
- '''
- def replay_back(epsilon, gamma, epislon_min, epsilon_decay, model, training_data,
- batch_size = 64):
- idx = random.sample(range(len(training_data)), min(len(training_data), batch_size))
- train_batch = [training_data[j] for j in idx]
- for state, new_state, reward, done, action in train_batch:
- target = reward
- '''
- 在当前状态(state)采取给定行动(action),进入下一个状态(next_state),
- 如果next_state不是终止状态,那意味着在在当前状态state采取给定行动action是正确的,
- 于是我们根据Bellman函数迭代更新当前状态采取给定行动后的回报,然后训练网络识别状态点,行动
- 以及回报之间存在的关系,然后根据这种训练后的能力去识别新状态点在采取不同行动后的回报
- '''
- if not done:
- # bellman函数迭代状态点执行给定行动后的回报
- target = reward + gamma * np.amax(model.predict(new_state)[0])
- target_f = model.predict(state)
- #修正网络在给定状态下对给定行动后回报的预测
- target_f[0][action] = target
- #让网络重新识别给定状态采取给定行动后所得回报间的联系
- model.fit(state, target_f, epochs = 1, verbose = 0)
- if epsilon > epsilon_min:
- #不断缩小epsilon的值,这样在agent_action中会更多的让网络做出决策
- epsilon *= epsilon_decay
- return epsilon
-
- # In[35]: 运行程序
-
- # 参数设置
- gamma = 0.90
- epsilon = 1.0
- epsilon_min = 0.01
- epsilon_decay = 0.99
- deque_len = 20000 # 训练集的样本数
-
- #我们的目标是训练网络能在一个episode中获得200分
- target_score = 200
- episodes = 2000 #2000,已改为2000
- batch_size = 64
- optimizer = 'adam'
- loss = 'mse'
-
- env = gym.make('CartPole-v1')
- seed_val = 456
- np.random.seed(seed_val)
- env.seed(seed_val)
- random.seed(seed_val)
-
- states = env.observation_space.shape[0]
- actions = env.action_space.n
- training_data = deque(maxlen=deque_len)
-
- if (1):
- print('---training---')
- K.clear_session()
- scores = []
- model = agent(states, actions)
- model.compile(loss = loss, optimizer = optimizer)
-
- for episode in range(1, episodes + 1):
- state = env.reset()
- #转换成1*4向量
- state = state.reshape(1, states)
- done = False
- time_step = 0
- while not done:
- #使用贪婪算法获得行动类型
- action = agent_action(model, epsilon, state, actions)
- new_state, reward, done, info = env.step(action)
- '''
- 如果当前行动导致的下个状态是终止状态,它对应的回报要对应负值
- '''
- reward = reward if not done else -10
- new_state = new_state.reshape(1, states)
-
- # 把状态转换信息存储起来用于训练网络
- # 当前状态,新状态,奖励,游戏是否结束,行动
- training_data.append((state, new_state, reward, done, action))
-
- state = new_state
- time_step += 1 # 当前网络下,走了多少步游戏终止,即获得的积分
-
- # 用所有的状态转换信息去训练网络
- epsilon = replay_back(epsilon, gamma, epsilon_min, epsilon_decay, model, training_data)
- scores.append(time_step)
- if episode % 100 == 0:
- print('episod {}, socre {}, epsilon {:4}'.format(episode, time_step,
- epsilon))
- print('Avg Score over last 100 epochs: ', sum(scores[-100:])/100)
- if sum(scores[-100: ])/100 > target_score:
- print('----Goal Achived After {} Episodes------'.format(episode))
- performance_plot(scores, target_score)
- break
- model.save('CartPole.h5')

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。