【强化学习实验】- 策略梯度算法

1.实验内容

策略梯度算法文章中2.2 策略梯度算法。

通俗总结

① 优胜劣汰

② 学如逆水行舟,不进则退。

2.实验目标

2.1 构建策略模型

python 复制代码
class PolicyNet(torch.nn.Module):
    def __init__(self, state_dim, hidden_dim, action_dim):
        super(PolicyNet, self).__init__()
        self.fc1 = torch.nn.Linear(state_dim, hidden_dim)
        self.fc2 = torch.nn.Linear(hidden_dim, action_dim)
    # 输入就是state, 输出就是一个action分布
    def forward(self, x):
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return F.softmax(x, dim=1)

2.2 目标函数 及其 loss函数

loss = -微分对象=-Q*log概率

python 复制代码
def update(self, transition_dict):
    state_list  = transition_dict['states']
    action_list = transition_dict['actions']
    reward_list = transition_dict['rewards']
    # 每个episode为单位, 计算动作价值的累计收益
    G = 0
    
    # 倒放数据,计算动作的累计收益
    self.optimizer.zero_grad()
    for i in range(len(reward_list)-1, -1, -1):
        state = torch.tensor([state_list[i]]).to(self.device)
        action = torch.tensor([action_list[i]]).view(-1, 1).to(self.device)
        G = reward_list[i] + self.gamma*G
        logP = torch.log(self.policy_net(state).gather(1, action))
        loss = -G*logP
        loss.backward()
    self.optimizer.step()

2.3 思考算法的优缺点

a、仅使用sar数据,可能会限制算法的能力上线

b、无偏,但是方差比较大

3.完整代码

见附件

4.实验结果

模型训练750个epoch接近收敛,而后震荡收敛。

尝试扩大epoch,效果如下:

结论:总的来说,可以收敛,但是收敛效果并不是很好,后续和AC算法做一下对比。

有没有小伙伴知道为啥后期收敛效果不好?欢迎评论指教。

相关推荐
_日拱一卒2 分钟前
LeetCode:最长连续序列
算法·leetcode·职场和发展
万里沧海寄云帆3 分钟前
pytorch+cpu版本对Intel Ultra 9 275HX性能的影响
人工智能·pytorch·python
2401_879503416 分钟前
C++与FPGA协同设计
开发语言·c++·算法
阿里云大数据AI技术6 分钟前
阿里云荣获 2025–2026 年度 Elastic中国最佳合作伙伴奖
人工智能·elasticsearch
yrwang_xd9 分钟前
人工智能基础-常用Nvidia Tesla及RTX显卡算力大全-2026版
人工智能
用户48159301959116 分钟前
MCP 终极指南(进阶篇):手写一个 MCP Server,再用抓包拆解协议底层
人工智能
用户48159301959116 分钟前
我抓包了 Cline 与模型的通信,发现了一件有趣的事
人工智能
重生之后端学习17 分钟前
287. 寻找重复数
数据结构·算法·leetcode·深度优先·图论
1941s18 分钟前
Google Agent Development Kit (ADK) 指南 第二章:环境搭建与快速开始
人工智能·python·adk·google agent
抓个马尾女孩21 分钟前
位置编码:绝对位置编码、相对位置编码、旋转位置编码
人工智能·深度学习·算法·transformer