import numpy as np
import gym
env = gym.make('CartPole-v1')
# Define the Q-learning parameters
alpha = 0.1 # Learning rate
gamma = 1 # Discount factor
epsilon = 0.2 # Epsilon-greedy parameter
episode_num = 20000
# state space: [postion, d_postion, angle, d_angle]
bin_num = [30, 30, 30, 30]
Q_matrix = np.random.uniform(0, 1, bin_num + [2]) # 2 for action space size
upper_bounds = env.observation_space.high
lower_bounds = env.observation_space.low
# to replace inf value
upper_bounds[1]=3
upper_bounds[3]=10
lower_bounds[1]=-3
lower_bounds[3]=-10
# bin table
cartPosition_bin = np.linspace(lower_bounds[0], upper_bounds[0], bin_num[0])
cartVelocity_bin = np.linspace(lower_bounds[1], upper_bounds[1], bin_num[1])
poleAngle_bin = np.linspace(lower_bounds[2], upper_bounds[2], bin_num[2])
poleAngleVelocity_bin = np.linspace(lower_bounds[3], upper_bounds[3], bin_num[3])
def get_state_index(state):
# avoiding idx < 0
cartPosition_bin_idx = np.maximum(np.digitize(state[0], cartPosition_bin) - 1, 0)
cartVelocity_bin_idx = np.maximum(np.digitize(state[1], cartVelocity_bin) - 1, 0)
poleAngle_bin_idx = np.maximum(np.digitize(state[2], poleAngle_bin) - 1, 0)
poleAngleVelocity_bin_idx = np.maximum(np.digitize(state[3], poleAngleVelocity_bin) - 1, 0)
return tuple([cartPosition_bin_idx, cartVelocity_bin_idx, poleAngle_bin_idx, poleAngleVelocity_bin_idx])
def select_action(state, episode_idx):
global epsilon
if episode_idx < 100:
return np.random.choice([0, 1])
elif episode_idx > 7000:
epsilon = 0.999 * epsilon
if np.random.uniform(0, 1) < epsilon:
action = np.random.choice([0, 1])
else:
state_idx = get_state_index(state)
action = np.argmax(Q_matrix[state_idx])
return action
rewards_list = []
for episode_idx in range(episode_num):
state, _ = env.reset()
episode_reward = 0
terminated = False
while not terminated:
action = select_action(state, episode_idx)
state_next, reward, terminated, truncat, _ = env.step(action)
state_idx = get_state_index(state)
state_next_idx = get_state_index(state_next)
if not (terminated or truncat): # is not the last state
Q_matrix[state_idx + (action,)] = (1 - alpha) * Q_matrix[state_idx + (action,)] + alpha * (reward + gamma * np.max(Q_matrix[state_next_idx]))
else: # is the last state
Q_matrix[state_idx + (action,)] = (1 - alpha) * Q_matrix[state_idx + (action,)] + alpha * reward
state = state_next
episode_reward += reward
print("Episode: {}, reward: {}".format(episode_idx, episode_reward))
rewards_list.append(episode_reward)
env.close()
# conclusion
import matplotlib.pyplot as plt
plt.plot(rewards_list)
plt.savefig("./out/rewards.png")
plt.show()
# save
import json
with open('./out/qmatrix.json', 'w') as f:
json.dump(Q_matrix.tolist(), f)
没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
【资源说明】 基于python实现Q-Learning算法训练倒立摆控制源码.zip基于python实现Q-Learning算法训练倒立摆控制源码.zip基于python实现Q-Learning算法训练倒立摆控制源码.zip基于python实现Q-Learning算法训练倒立摆控制源码.zip基于python实现Q-Learning算法训练倒立摆控制源码.zip基于python实现Q-Learning算法训练倒立摆控制源码.zip基于python实现Q-Learning算法训练倒立摆控制源码.zip 基于python实现Q-Learning算法训练倒立摆控制源码.zip 基于python实现Q-Learning算法训练倒立摆控制源码.zip 基于python实现Q-Learning算法训练倒立摆控制源码.zip 【备注】 1.项目代码均经过功能验证ok,确保稳定可靠运行。欢迎下载使用体验! 2.主要针对各个计算机相关专业,包括计算机科学、信息安全、数据科学与大数据技术、人工智能、通信、物联网等领域的在校学生、专业教师、企业员工。 3.项目具有丰富的拓展空间,不仅可作为入门进阶,也可直接作为毕设、课程设计、大作业、初期项目立项演示等用途。 4.当然也鼓励大家基于此进行二次开发。在使用过程中,如有问题或建议,请及时沟通。 5.期待你能在项目中找到乐趣和灵感,也欢迎你的分享和反馈!
资源推荐
资源详情
资源评论
收起资源包目录
基于python实现Q-Learning算法训练倒立摆控制源码.zip (7个子文件)
out
rewards.png 24KB
qmatrix.json 32.91MB
cartpole_run.py 1KB
img
ballman.png 92KB
cartpole.png 33KB
使用说明.md 664B
cartpole_train.py 3KB
共 7 条
- 1
资源评论
北航程序员小C
- 粉丝: 2222
- 资源: 1823
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功