0
点赞
收藏
分享

微信扫一扫

强化学习算法介绍和代码例程


强化学习(Reinforcement Learning, RL)是一种机器学习方法,通过代理与环境的交互来学习如何做出决策以最大化累积奖励。在强化学习中,代理根据观测到的状态选择动作,并获得环境反馈的奖励或惩罚,从而调整策略以实现长期回报最大化的目标。

以下是一个简单的Python代码例程,使用OpenAI Gym库实现一个基本的强化学习算法(Q-learning)来解决CartPole问题:

# 导入必要的库
import gym
import numpy as np

# 创建CartPole环境
env = gym.make('CartPole-v1')

# 定义Q-learning算法
def q_learning(env, learning_rate=0.1, discount_factor=0.95, epsilon=0.1, num_episodes=1000):
    # 初始化Q表格
    action_space_size = env.action_space.n
    state_space_size = env.observation_space.shape[0]
    q_table = np.zeros((state_space_size, action_space_size))
    
    # 训练Q-learning算法
    for episode in range(num_episodes):
        state = env.reset()
        done = False
        
        while not done:
            # 选择动作
            if np.random.uniform(0, 1) < epsilon:
                action = env.action_space.sample()  # 探索
            else:
                action = np.argmax(q_table[state, :])  # 利用
            
            next_state, reward, done, _ = env.step(action)
            
            # 更新Q值
            q_table[state, action] += learning_rate * (reward + discount_factor * np.max(q_table[next_state, :]) - q_table[state, action])
            
            state = next_state
    
    return q_table

# 运行Q-learning算法并获取最优策略
q_table = q_learning(env)

# 使用最优策略演示
state = env.reset()
done = False
total_reward = 0

while not done:
    action = np.argmax(q_table[state, :])
    state, reward, done, _ = env.step(action)
    total_reward += reward

print("Total reward: ", total_reward)

在这个例程中,我们首先创建了CartPole环境,然后定义了一个简单的Q-learning算法来训练代理在CartPole问题上学习最优策略。最后使用学习到的最优Q值表来运行代理并输出总奖励。你可以根据需要调整学习率、折扣因子、探索率以及训练次数来应用强化学习算法解决不同的问题。


举报

相关推荐

0 条评论