强化学习------Qlearning算法

简介

Q learning 算法是一种value-based的强化学习算法,Q是quality的缩写,Q函数 Q(state,action)表示在状态state下执行动作actionquality, 也就是能获得的Q value是多少。算法的目标是最大化Q值,通过在状态state下所有可能的动作中选择最好的动作来达到最大化期望reward

Q learning算法使用Q table来记录不同状态下不同动作的预估Q值。在探索环境之前,Q table会被随机初始化,当agent在环境中探索的时候,它会用贝尔曼方程(ballman equation)来迭代更新Q(s,a), 随着迭代次数的增多,agent会对环境越来越了解,Q 函数也能被拟合得越来越好,直到收敛或者到达设定的迭代结束次数。
伪代码如下:
在这里插入图片描述
整个算法就是一直不断更新 Q table 里的值, 然后再根据新的值来判断要在某个 state 采取怎样的 action. Qlearning 是一个 off-policy 的算法, 因为里面的 max action 让 Q table 的更新可以不基于正在经历的经验(可以是现在学习着很久以前的经验,甚至是学习他人的经验). 不过这一次的例子, 我们没有运用到 off-policy, 而是把 Qlearning 用在了 on-policy 上, 也就是现学现卖, 将现在经历的直接当场学习并运用. On-policy 和 off-policy 的差别我们会在之后的 [Deep Q network (off-policy)] 学习中见识到. 而之后的教程也会讲到一个 on-policy (Sarsa) 的形式, 我们之后再对比.

算法实战

我们使用openAI的gym中的CliffWalking-v0作为环境

#!/usr/bin/env python 
# -*- coding:utf-8 -*-
import numpy as np
import gym
import time
import gridworld#Sarsa算法
class QLearning():def __init__(self,num_states,num_actions,e_greed=0.1,lr=0.9,gamma=0.8):#建立Q表格self.Q = np.zeros((num_states,num_actions))self.e_greed = e_greed   #探索概率self.num_states = num_statesself.num_actions = num_actionsself.lr = lr   #学习率self.gamma = gamma #折扣因子def predict(self,state):"""通过当前状态预测下一个动作:param state::return:"""#获取当前状态的所有动作的切片Q_list = self.Q[state,:]#随机选取其中最大值中的某一个(防止存在多个最大值时,总是选最前面的问题)action = np.random.choice(np.flatnonzero(Q_list == Q_list.max()))return  actiondef action(self,state):"""选取动作:param state::return:"""#探索,随机选择一个动作if np.random.uniform(0,1) < self.e_greed:action = np.random.choice(self.num_actions)else:   #直接选取最大Q值的动作action = self.predict(state)return actiondef learn(self,state,action,reward,next_state,done):cur_Q = self.Q[state,action]# 当游戏结束时,不存在next_action和next_statetarget_Q = reward + (1-float(done))*self.gamma*self.Q[next_state,:].max()self.Q[state,action] += self.lr*(target_Q - cur_Q)#训练
def train_episode(env,agent,is_render):total_reward = 0#初始化环境state,_ = env.reset()while True:action = agent.action(state)#执行动作返回结果next_state,reward,done,_,_ = env.step(action)#更新参数agent.learn(state,action,reward,next_state,done)#循环执行state = next_statetotal_reward += rewardif is_render:env.render()if done:breakreturn  total_reward
#测试
def test_episode(env,agent,is_render=False):total_reward = 0# 初始化环境state,_ = env.reset()while True:action = agent.predict(state)next_state, reward, done, _,_ = env.step(action)state = next_statetotal_reward += rewardenv.render()time.sleep(0.5)if done:breakreturn total_reward
#训练
def train(env,episodes=500,lr=0.1,gamma=0.9,e_greed=0.1):agent = QLearning(num_states = env.observation_space.n,num_actions = env.action_space.n,lr = lr,gamma = gamma,e_greed = e_greed)is_render = False#先训练episodes次for e in range(episodes):ep_reward = train_episode(env,agent,is_render)print('Episode %s : reward= %.1f'%(e,ep_reward))#每执行50轮就显示一次if e%50 == 0:is_render = Trueelse:is_render = False#训练结束后,我i们测试模型test_reward = test_episode(env,agent)print('test_reward= %.1f' % (test_reward))if __name__ == '__main__':env = gym.make("CliffWalking-v0")env = gridworld.CliffWalkingWapper(env)train(env)

运行效果

在这里插入图片描述

另附工具类

用于可视化游戏界面

#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.# -*- coding: utf-8 -*-import gym
import turtle
import numpy as np# turtle tutorial : https://docs.python.org/3.3/library/turtle.htmldef GridWorld(gridmap=None, is_slippery=False):if gridmap is None:gridmap = ['SFFF', 'FHFH', 'FFFH', 'HFFG']env = gym.make("FrozenLake-v0", desc=gridmap, is_slippery=False)env = FrozenLakeWapper(env)return envclass FrozenLakeWapper(gym.Wrapper):def __init__(self, env):gym.Wrapper.__init__(self, env)self.max_y = env.desc.shape[0]self.max_x = env.desc.shape[1]self.t = Noneself.unit = 50def draw_box(self, x, y, fillcolor='', line_color='gray'):self.t.up()self.t.goto(x * self.unit, y * self.unit)self.t.color(line_color)self.t.fillcolor(fillcolor)self.t.setheading(90)self.t.down()self.t.begin_fill()for _ in range(4):self.t.forward(self.unit)self.t.right(90)self.t.end_fill()def move_player(self, x, y):self.t.up()self.t.setheading(90)self.t.fillcolor('red')self.t.goto((x + 0.5) * self.unit, (y + 0.5) * self.unit)def render(self):if self.t == None:self.t = turtle.Turtle()self.wn = turtle.Screen()self.wn.setup(self.unit * self.max_x + 100,self.unit * self.max_y + 100)self.wn.setworldcoordinates(0, 0, self.unit * self.max_x,self.unit * self.max_y)self.t.shape('circle')self.t.width(2)self.t.speed(0)self.t.color('gray')for i in range(self.desc.shape[0]):for j in range(self.desc.shape[1]):x = jy = self.max_y - 1 - iif self.desc[i][j] == b'S':  # Startself.draw_box(x, y, 'white')elif self.desc[i][j] == b'F':  # Frozen iceself.draw_box(x, y, 'white')elif self.desc[i][j] == b'G':  # Goalself.draw_box(x, y, 'yellow')elif self.desc[i][j] == b'H':  # Holeself.draw_box(x, y, 'black')else:self.draw_box(x, y, 'white')self.t.shape('turtle')x_pos = self.s % self.max_xy_pos = self.max_y - 1 - int(self.s / self.max_x)self.move_player(x_pos, y_pos)class CliffWalkingWapper(gym.Wrapper):def __init__(self, env):gym.Wrapper.__init__(self, env)self.t = Noneself.unit = 50self.max_x = 12self.max_y = 4def draw_x_line(self, y, x0, x1, color='gray'):assert x1 > x0self.t.color(color)self.t.setheading(0)self.t.up()self.t.goto(x0, y)self.t.down()self.t.forward(x1 - x0)def draw_y_line(self, x, y0, y1, color='gray'):assert y1 > y0self.t.color(color)self.t.setheading(90)self.t.up()self.t.goto(x, y0)self.t.down()self.t.forward(y1 - y0)def draw_box(self, x, y, fillcolor='', line_color='gray'):self.t.up()self.t.goto(x * self.unit, y * self.unit)self.t.color(line_color)self.t.fillcolor(fillcolor)self.t.setheading(90)self.t.down()self.t.begin_fill()for i in range(4):self.t.forward(self.unit)self.t.right(90)self.t.end_fill()def move_player(self, x, y):self.t.up()self.t.setheading(90)self.t.fillcolor('red')self.t.goto((x + 0.5) * self.unit, (y + 0.5) * self.unit)def render(self):if self.t == None:self.t = turtle.Turtle()self.wn = turtle.Screen()self.wn.setup(self.unit * self.max_x + 100,self.unit * self.max_y + 100)self.wn.setworldcoordinates(0, 0, self.unit * self.max_x,self.unit * self.max_y)self.t.shape('circle')self.t.width(2)self.t.speed(0)self.t.color('gray')for _ in range(2):self.t.forward(self.max_x * self.unit)self.t.left(90)self.t.forward(self.max_y * self.unit)self.t.left(90)for i in range(1, self.max_y):self.draw_x_line(y=i * self.unit, x0=0, x1=self.max_x * self.unit)for i in range(1, self.max_x):self.draw_y_line(x=i * self.unit, y0=0, y1=self.max_y * self.unit)for i in range(1, self.max_x - 1):self.draw_box(i, 0, 'black')self.draw_box(self.max_x - 1, 0, 'yellow')self.t.shape('turtle')x_pos = self.s % self.max_xy_pos = self.max_y - 1 - int(self.s / self.max_x)self.move_player(x_pos, y_pos)if __name__ == '__main__':# 环境1:FrozenLake, 可以配置冰面是否是滑的# 0 left, 1 down, 2 right, 3 upenv = gym.make("FrozenLake-v0", is_slippery=False)env = FrozenLakeWapper(env)# 环境2:CliffWalking, 悬崖环境# env = gym.make("CliffWalking-v0")  # 0 up, 1 right, 2 down, 3 left# env = CliffWalkingWapper(env)# 环境3:自定义格子世界,可以配置地图, S为出发点Start, F为平地Floor, H为洞Hole, G为出口目标Goal# gridmap = [#         'SFFF',#         'FHFF',#         'FFFF',#         'HFGF' ]# env = GridWorld(gridmap)env.reset()for step in range(10):action = np.random.randint(0, 4)obs, reward, done, info = env.step(action)print('step {}: action {}, obs {}, reward {}, done {}, info {}'.format(\step, action, obs, reward, done, info))env.render()  # 渲染一帧图像

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/97669.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

html通过使用图像源的协议(protocol)相对 URL 来防止安全/不安全错误

有人知道使用 protocol relative URLs 是否有问题吗&#xff1f;用于图像源以防止混合内容安全警告。 例如链接一张图片: <img src"//domain.com/img.jpg" /> 代替: <img src"http://domain.com/img.jpg" /> or <img src"https…

day10.8ubentu流水灯

流水灯 .text .global _start _start: 1.设置GPIOE寄存器的时钟使能 RCC_MP_AHB4ENSETR[4]->1 0x50000a28LDR R0,0X50000A28LDR R1,[R0] 从r0为起始地址的4字节数据取出放在R1ORR R1,R1,#(0x1<<4) 第4位设置为1STR R1,[R0] 写回2.设置PE10管脚为输出模式 G…

Android多线程学习:线程

一、概念 进程&#xff1a;系统资源分配的基本单位&#xff0c;进程之间相互独立&#xff0c;不能直接访问其他进程的地址空间。 线程&#xff1a;CPU调度的基本单位&#xff0c;线程之间共享所在进程的资源&#xff0c;包括共享内存&#xff0c;公有数据&#xff0c;全局变量…

10.8c++作业

#include <iostream>using namespace std; class Rect {int width; //宽int height; //高 public://初始化函数void init(int w,int h){widthw;heighth;}//更改宽度void set_w(int w){widthw;}//更改高度void set_h(int h){heighth;}//输出矩形周长和面积void show(){co…

ASO优化之应用程序图标的设计技巧

用户在App Store页面上&#xff0c;首先看到的是我们的移动应用程序图标&#xff0c;所以应用图标的设计至关重要。如果这不能引起用户的注意&#xff0c;他们可能不会费心去了解有关我们的应用的更多信息。 1、脱颖而出的重要性。 具有附加价值&#xff0c;如果做得好&#x…

bigemap在林业勘测规划设计行业的一些应用

选择Bigemap的原因&#xff1a; 主要注重影像的时效性&#xff0c;软件的影像时效性比其他的更新快&#xff0c;更清晰。 使用场景&#xff1a; 1.林业督查&#xff0c;主要是根据国家下发的图斑&#xff0c;结合测绘局的影像以及bigemap的较新影像对比去年和今年的林地变化。…

MySQL——使用mysqldump备份与恢复数据

目录 1.mysqldump简介 2.mysqldump备份数据 2.1 备份所有数据库 2.2 备份一个/多个数据库 2.3 备份指定库中的指定表 3.mysqldump恢复数据 3.1 恢复数据库 3.2 恢复数据表 1.mysqldump简介 mysqldump命令可以将数据库中指定或所有的库、表导出为SQL脚本。表的结构和表中…

Survey on Cooperative Perception in an Automotive Context 论文阅读

论文链接 Survey on Cooperative Perception in an Automotive Context 0. Abstract 本文就协同基础设施领域提供相关环境的调查回顾了感知中涉及的主要模块&#xff1a;定位&#xff0c;目标检测和跟踪&#xff0c;地图生成提供了协同感知的 SWOT 1. Intro 无人驾驶汽车的背…

力扣 -- 647. 回文子串

解题步骤&#xff1a; 参考代码&#xff1a; class Solution { public:int countSubstrings(string s) {int ns.size();vector<vector<bool>> dp(n,vector<bool>(n));//无需初始化int ret0;//一定要从下往上填写每一行for(int in-1;i>0;i--){//每一行的i…

Acwing.889 满足条件的01序列

题目 给定n个0和n个1&#xff0c;它们将按照某种顺序排成长度为2n的序列&#xff0c;求它们能排列成的所有序列中&#xff0c;能够满足任意前缀序列中0的个数都不少于1的个数的序列有多少个。 输出的答案对109&#xff0b;7取模。 输入格式 共一行&#xff0c;包含整数n。 …

嵌入式Linux裸机开发(一)基础介绍及汇编LED驱动

系列文章目录 文章目录 系列文章目录前言IMX6ULL介绍主要资料IO表现形式 汇编LED驱动原理图初始化流程时钟设置IO复用设置电气属性设置使用GPIO 编写驱动编译程序编译.o文件地址链接.elf格式转换.bin反汇编&#xff08;其他&#xff09; 综合成Makefile完成一步编译烧录程序imx…

电脑挂代理问题解析:如何应对常见疑难杂症

使用代理对电脑进行网络访问是保护个人隐私、绕过封锁等常用策略。然而&#xff0c;在实际应用中可能会遇到各种问题&#xff0c;如连接失败、速度缓慢等疑难杂症。本文将为您解析电脑挂代理时常见问题的原因&#xff0c;并分享解决方案&#xff0c;帮助您应对这些困扰&#xf…

物联网通信技术课程作业资料(TPUNB技术)

参考内容 TPUNB无线通信技术 - 技象科技 (techphant.cn) 技象科技CTO郑凛&#xff1a;用最好的物联网服务最多的人 | 了不起的创变者_技术_通信_团队 (sohu.com) LPWAN技术融合使用大势之下&#xff0c;TPUNB奔跑的一年-IOTE物联网展 (baidu.com) 院士认可国际首创&#xf…

CobalStrike(CS)流量分析

​ 目录 0x01声明: 0x02简介: 0x03环境搭建: 0x04流量分析: 心跳包特征:

经典循环神经网络(一)RNN及其在歌词数据集上的应用

经典循环神经网络(一)RNN及其在歌词数据集上的应用 1 RNN概述 在深度学习兴起之前&#xff0c;NLP领域一直是统计模型的天下&#xff0c;例如词对齐算法GIZA&#xff0c;统计机器翻译开源框架MOSES等等。在语言模型方向&#xff0c;n-gram是当时最为流行的语言模型方法。n-gr…

计算机竞赛 题目:基于卷积神经网络的手写字符识别 - 深度学习

文章目录 0 前言1 简介2 LeNet-5 模型的介绍2.1 结构解析2.2 C1层2.3 S2层S2层和C3层连接 2.4 F6与C5层 3 写数字识别算法模型的构建3.1 输入层设计3.2 激活函数的选取3.3 卷积层设计3.4 降采样层3.5 输出层设计 4 网络模型的总体结构5 部分实现代码6 在线手写识别7 最后 0 前言…

Sql和NoSql

Sql和NoSql SQL使用&#xff1a;如果有大量的更新操作&#xff0c;一定要使用事务&#xff0c;效率高。大数据情况下&#xff0c;要对表字段建索引。比nosql好的地方&#xff1a;有事务&#xff0c;能回滚。 SQL遇到的瓶颈&#xff1a;水平扩展 场景&#xff1a;不同设备&am…

全面解析UDP协议(特点、报文格式、UDP和TCP的区别)

了解UDP&#xff08;User Datagram Protocol&#xff09; UDP是无连接通信协议&#xff0c;即在数据传输时&#xff0c;数据的发送端和接收端不建立逻辑连接。简单来说&#xff0c;当一台计算机向另外一台计算机发送数据时&#xff0c;发送端不会确认接收端是否存在&#xff0…

【洛谷】P1114 “非常男女”计划

思路&#xff1a;思路和上一篇一模一样哒~&#xff08;这里就不多解释啦&#xff09; ACcode: #include <iostream> #include <cstring> #include <algorithm> using namespace std; const int N 2e510; int n,a[N],f[N]; int main() { ios::sync_with_st…

[洛谷]P1440 求m区间内的最小值(线段树)

板子题~ ACcode: #include<bits/stdc.h> using namespace std; const int N 2e610; typedef long long ll; #define int long long struct node{int l,r;int minv; }tr[N*4]; int n,m,w[N]; void pushup(int u){tr[u].minvmin(tr[u<<1].minv,tr[u<<1|1].m…