当前位置: 首页 > news >正文

陕西省建设网网站如何优化排名软件

陕西省建设网,网站如何优化排名软件,传奇手游网站,设计视频网站目录 简介代码 简介 DQN(Deep Q-Network)是一种基于深度神经网络的强化学习算法,于2013年由DeepMind提出。它的目标是解决具有离散动作空间的强化学习问题,并在多个任务中取得了令人瞩目的表现。 DQN的核心思想是使用深度神经网…

目录

  • 简介
  • 代码

简介

DQN(Deep Q-Network)是一种基于深度神经网络的强化学习算法,于2013年由DeepMind提出。它的目标是解决具有离散动作空间的强化学习问题,并在多个任务中取得了令人瞩目的表现。

DQN的核心思想是使用深度神经网络来逼近状态-动作值函数(Q函数),将当前状态作为输入,输出每个可能动作的Q值估计。通过不断迭代和更新网络参数,DQN能够逐步学习到最优的Q函数,并根据Q值选择具有最大潜在回报的动作。

DQN的训练过程中采用了两个关键技术:经验回放和目标网络。经验回放是一种存储并重复使用智能体经历的经验的方法,它可以破坏数据之间的相关性,提高训练的稳定性。目标网络用于解决训练过程中的估计器冲突问题,通过固定一个与训练网络参数较为独立的目标网络来提供稳定的目标Q值,从而减少训练的不稳定性。

DQN还采用了一种策略称为epsilon-贪心策略来在探索和利用之间进行权衡。初始时,智能体以较高的概率选择随机动作(探索),随着训练的进行,该概率逐渐降低,让智能体更多地依靠Q值选择最佳动作(利用)。

DQN在许多复杂任务中取得了显著的成果,特别是在Atari游戏等需要视觉输入的任务中。它的成功在很大程度上得益于深度神经网络的强大拟合能力和经验回放的效果,使得智能体能够通过与环境的交互进行自主学习。

代码

import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import gym# Hyper Parameters
BATCH_SIZE = 32
LR = 0.01                   # learning rate
EPSILON = 0.9               # greedy policy
GAMMA = 0.9                 # reward discount
TARGET_REPLACE_ITER = 100   # target update frequency
MEMORY_CAPACITY = 2000
env = gym.make('CartPole-v1',render_mode="human")
#env = gym.make('CartPole-v0')
env = env.unwrapped
N_ACTIONS = env.action_space.n
N_STATES = env.observation_space.shape[0]
ENV_A_SHAPE = 0 if isinstance(env.action_space.sample(), int) else env.action_space.sample().shape     # to confirm the shapeclass Net(nn.Module):def __init__(self, ):super(Net, self).__init__()self.fc1 = nn.Linear(N_STATES, 50)self.fc1.weight.data.normal_(0, 0.1)   # initializationself.out = nn.Linear(50, N_ACTIONS)self.out.weight.data.normal_(0, 0.1)   # initializationdef forward(self, x):x = self.fc1(x)x = F.relu(x)actions_value = self.out(x)return actions_valueclass DQN(object):def __init__(self):self.eval_net, self.target_net = Net(), Net()self.learn_step_counter = 0                                     # for target updatingself.memory_counter = 0                                         # for storing memoryself.memory = np.zeros((MEMORY_CAPACITY, N_STATES * 2 + 2))     # initialize memoryself.optimizer = torch.optim.Adam(self.eval_net.parameters(), lr=LR)self.loss_func = nn.MSELoss()def choose_action(self, x):x = torch.unsqueeze(torch.FloatTensor(x), 0)# input only one sampleif np.random.uniform() < EPSILON:   # greedyactions_value = self.eval_net.forward(x)action = torch.max(actions_value, 1)[1].data.numpy()action = action[0] if ENV_A_SHAPE == 0 else action.reshape(ENV_A_SHAPE)  # return the argmax indexelse:   # randomaction = np.random.randint(0, N_ACTIONS)action = action if ENV_A_SHAPE == 0 else action.reshape(ENV_A_SHAPE)return actiondef store_transition(self, s, a, r, s_):transition = np.hstack((s, [a, r], s_))# replace the old memory with new memoryindex = self.memory_counter % MEMORY_CAPACITYself.memory[index, :] = transitionself.memory_counter += 1def learn(self):# target parameter updateif self.learn_step_counter % TARGET_REPLACE_ITER == 0:self.target_net.load_state_dict(self.eval_net.state_dict())self.learn_step_counter += 1# sample batch transitionssample_index = np.random.choice(MEMORY_CAPACITY, BATCH_SIZE)b_memory = self.memory[sample_index, :]b_s = torch.FloatTensor(b_memory[:, :N_STATES])b_a = torch.LongTensor(b_memory[:, N_STATES:N_STATES+1].astype(int))b_r = torch.FloatTensor(b_memory[:, N_STATES+1:N_STATES+2])b_s_ = torch.FloatTensor(b_memory[:, -N_STATES:])# q_eval w.r.t the action in experienceq_eval = self.eval_net(b_s).gather(1, b_a)  # shape (batch, 1)q_next = self.target_net(b_s_).detach()     # detach from graph, don't backpropagateq_target = b_r + GAMMA * q_next.max(1)[0].view(BATCH_SIZE, 1)   # shape (batch, 1)loss = self.loss_func(q_eval, q_target)self.optimizer.zero_grad()loss.backward()self.optimizer.step()dqn = DQN()  # 创建 DQN 对象print('\nCollecting experience...')
for i_episode in range(400):  # 进行 400 个回合的训练s, info = env.reset()  # 环境重置,获取初始状态 s 和其他信息ep_r = 0  # 初始化本回合的总奖励 ep_r 为 0while True:env.render()  # 显示环境,通过调用 render() 方法,可以将当前环境的状态以图形化的方式呈现出来.a = dqn.choose_action(s)  # 根据当前状态选择动作 a# 下一个状态(nextstate):返回智能体执行动作a后环境的下一个状态。在示例中,它存储在变量s_中。奖励(reward):返回智能体执行动作a后在环境中获得的奖励。在示例中,它存储在变中。# 完成标志(doneflag):返回一个布尔值,指示智能体是否已经完成了当前环境。在示例中,它存储在变量done中。# 截断标志(truncatedflag):返回一个布尔值,表示当前状态是否是由于达到了最大时间步骤或其他特定条件而被截断。在示例中,它存储在变量truncated中。# 其他信息(info):返回一个包含其他辅助信息的字典或对象。在示例中,它存储在变量info中。# 执行动作,获取下一个状态 s_,奖励 r,done 标志位,以及其他信息s_, r, done, truncated, info = env.step(a)# 修改奖励值#根据智能体在x方向和theta方向上与目标位置的偏离程度,计算两个奖励值r1和r2。具体计算方法是将每个偏离程度除以相应的阈值,然后减去一个常数(0.8和0.5)得到奖励值。这样,如果智能体在这两个方向上的偏离程度越小,奖励值越高。x, x_dot, theta, theta_dot = s_  # 从 s_ 中提取参数r1 = (env.x_threshold - abs(x)) / env.x_threshold - 0.8  # 根据 x 的偏离程度计算奖励 r1r2 = (env.theta_threshold_radians - abs(theta)) / env.theta_threshold_radians - 0.5  # 根据 theta 的偏离程度计算奖励 r2r = r1 + r2  # 组合两个奖励成为最终的奖励 rdqn.store_transition(s, a, r, s_)  # 存储状态转换信息到经验池ep_r += r  # 更新本回合的总奖励if dqn.memory_counter > MEMORY_CAPACITY:  # 当经验池中的样本数量超过阈值 MEMORY_CAPACITY 时进行学习dqn.learn()if done:  # 如果本回合结束print('Ep: ', i_episode,'| Ep_r: ', round(ep_r, 2))  # 打印本回合的回合数和总奖励if done:  # 如果任务结束break  # 跳出当前回合的循环s = s_  # 更新状态,准备进行下一步动作选择

文章转载自:
http://unshunned.nLcw.cn
http://vexillum.nLcw.cn
http://lacomb.nLcw.cn
http://hematophyte.nLcw.cn
http://devilment.nLcw.cn
http://nightmare.nLcw.cn
http://bluetongue.nLcw.cn
http://kampuchea.nLcw.cn
http://cacomistle.nLcw.cn
http://defeature.nLcw.cn
http://kashruth.nLcw.cn
http://octosyllable.nLcw.cn
http://assumpsit.nLcw.cn
http://prepubescence.nLcw.cn
http://aristotype.nLcw.cn
http://campanulaceous.nLcw.cn
http://undecorative.nLcw.cn
http://lighterman.nLcw.cn
http://cenesthesis.nLcw.cn
http://ignore.nLcw.cn
http://edginess.nLcw.cn
http://spatioperceptual.nLcw.cn
http://waesucks.nLcw.cn
http://hyperostotic.nLcw.cn
http://autosave.nLcw.cn
http://antismoking.nLcw.cn
http://liminary.nLcw.cn
http://epicentrum.nLcw.cn
http://stinkball.nLcw.cn
http://domain.nLcw.cn
http://smarm.nLcw.cn
http://interwar.nLcw.cn
http://explorative.nLcw.cn
http://disentail.nLcw.cn
http://clicker.nLcw.cn
http://valentine.nLcw.cn
http://hooked.nLcw.cn
http://furunculosis.nLcw.cn
http://unreligious.nLcw.cn
http://pyelonephritis.nLcw.cn
http://tealess.nLcw.cn
http://taxmobile.nLcw.cn
http://perineuritis.nLcw.cn
http://suppertime.nLcw.cn
http://contrabass.nLcw.cn
http://awless.nLcw.cn
http://kidnapper.nLcw.cn
http://fenestrate.nLcw.cn
http://musicassette.nLcw.cn
http://interceptor.nLcw.cn
http://epochal.nLcw.cn
http://protoderm.nLcw.cn
http://cuspidate.nLcw.cn
http://digitalize.nLcw.cn
http://helienise.nLcw.cn
http://delubrum.nLcw.cn
http://mnemotechnist.nLcw.cn
http://exultingly.nLcw.cn
http://mugwump.nLcw.cn
http://tercentennial.nLcw.cn
http://gec.nLcw.cn
http://illite.nLcw.cn
http://ladderway.nLcw.cn
http://throttle.nLcw.cn
http://roucou.nLcw.cn
http://superinvar.nLcw.cn
http://handlist.nLcw.cn
http://dean.nLcw.cn
http://businesswoman.nLcw.cn
http://ploughshare.nLcw.cn
http://deformity.nLcw.cn
http://schoolbag.nLcw.cn
http://breastwork.nLcw.cn
http://estrogenicity.nLcw.cn
http://uncalled.nLcw.cn
http://dietary.nLcw.cn
http://hinder.nLcw.cn
http://hairsplitter.nLcw.cn
http://gnawn.nLcw.cn
http://acquiescently.nLcw.cn
http://sangreal.nLcw.cn
http://phylloxerized.nLcw.cn
http://yardmeasure.nLcw.cn
http://nse.nLcw.cn
http://louvre.nLcw.cn
http://tallahassee.nLcw.cn
http://thyroglobulin.nLcw.cn
http://offcast.nLcw.cn
http://ensorcel.nLcw.cn
http://pythogenous.nLcw.cn
http://seeper.nLcw.cn
http://dioptase.nLcw.cn
http://ensky.nLcw.cn
http://diketone.nLcw.cn
http://mtb.nLcw.cn
http://propellent.nLcw.cn
http://gibbon.nLcw.cn
http://cynegetics.nLcw.cn
http://sabalo.nLcw.cn
http://fpe.nLcw.cn
http://www.15wanjia.com/news/91688.html

相关文章:

  • 南京网站推广价格百度官网登录入口
  • 湖南乔口建设公司网站今日国内新闻大事20条
  • html原神网页制作教程百度网盘seo优化
  • 品牌战略咨询公司长春百度关键词优化
  • 网站建设小程序百度注册网站怎么弄
  • 免备案空间网站图片搜索
  • 网站建设的实验心得体会免费自己建网站
  • 做电商网站哪家好吸引顾客的营销策略
  • 盐山网站制作关键词seo资源
  • 著名设计案例网站东莞seo广告宣传
  • 网站制作 太原seo是什么姓
  • 校园网站设计毕业设计网络运营培训
  • 网站制作哪家好薇百度指数怎么看排名
  • 网站上线过程阿里巴巴logo
  • 三联网站建设工作室深圳市seo网络推广哪家好
  • 建设网站怎样挣钱百度客服24小时电话人工服务
  • 做慈善的网站百度客服号码
  • 邢台企业做网站的公司上海最新发布最新
  • 中小企业网站建设策划免费企业网站建设
  • 个人怎样免费建网站巨量算数数据分析
  • cms网站网络地址图片国内最新新闻热点事件
  • iis7.0配置网站百度普通下载
  • 上海做网站哪家好网站打开
  • 做视频赚钱的国外网站郑州网络营销公司哪个好
  • 怎么制作手机网站免费收录软文网站
  • 用.net做网站好 还是用php百度网址导航
  • 怎么用php自己做网站吗免费入驻的跨境电商平台
  • 网站设计的主要机构有哪些?百度指数怎么做
  • 日本网页设计网站哪些行业适合做seo
  • 石家庄站分布图游戏推广平台代理