在网上找的各种dqn代码修改而成,只实现了基本功能,对各个游戏的适配性没有进行,代码中还存在各种bug,属于草稿品质,不适合fellow,只是一时学习之用而进行尝试的残次半成品。核心代码已实现,为DQN2013版本,后端用的是pytorch框架。

代码分享在:

https://gitee.com/devilmaycry812839668/bug-dqn2013

该代码并不完善,没有follow价值,只为学习之用。

========================================

从这个项目中还是学到了一些新的知识:

从模块  finished_tester.py   中可以看到opencv的图片保存为视频的操作:

from tqdm import trange
import numpy as np
import time
import cv2
import torch from config import args
from utils import seed_device_config
from agent import Agent
from environment import ALE # Configuration for log format&file, seed, torch
seed_device_config()
args.render = True
args.debug = True data_path = 'videos/'
fps = 30 #0.03333s fps=20 0.05s
size = (160, 210)
video = cv2.VideoWriter(f"{data_path+args.game}.avi", cv2.VideoWriter_fourcc(*'XVID'), fps, size) class ENV(ALE):
def step(self, action):
reward, done = 0, False
frame_buffer = np.zeros((2, 84, 84), dtype=np.uint8) for t in range(self.action_repeat):
reward += self.ale.act(self.actions[action])
frame_buffer[t % 2] = self._resize_state()
done = self.ale.game_over() lives = self.ale.lives()
if lives < self.lives:
if lives > 0:
self.life_termination = True
done = True
if done:
break observation = frame_buffer.max(0)
self.state_buffer.append(observation) if reward != 0:
print("reward: ", reward, "lives: ", lives, " done: ", self.ale.game_over())
reward = reward // abs(reward) return np.stack(self.state_buffer), reward, done env = ENV() # Agent
agt = Agent()
dqn = agt.dqn
p = "/home/devil/pycharm_project_857/exp/breakout/440935/2022_01_31-14_12_34/"+"3200000_model.pth"
dqn.load_state_dict(torch.load(p)) T_rewards = []
state, reward_sum, done = env.reset(), 0, False ts = 0.05
if args.render:
env.render()
time.sleep(ts) for step in range(args.evaluation_steps):
# for _ in trange(args.evaluation_steps):
action = agt.act_e_greedy(state)
state, reward, done = env.step(action)
reward_sum += reward if args.render:
env.render()
img = env.ale.getScreenRGB()[:, :, ::-1]
video.write(img)
time.sleep(ts)
if done:
print("reward_sum: ", reward_sum, " steps: ", step, " lives: ", env.ale.lives())
T_rewards.append(reward_sum)
state, reward_sum, done = env.reset(), 0, False if args.render:
env.render()
img = env.ale.getScreenRGB()[:, :, ::-1]
video.write(img)
time.sleep(ts) avg_reward = sum(T_rewards) / max(1, len(T_rewards))
print(avg_reward) if args.render:
env.close()
video.release() """
import cv2
import atari_py
import matplotlib.pyplot as plt
%matplotlib inline ale = atari_py.ALEInterface()
ale.loadROM(atari_py.get_game_path('breakout')) state = cv2.resize(
ale.getScreenGrayscale(),
(84, 110),
interpolation=cv2.INTER_LINEAR)
state = state[26:, :]
plt.imshow(state)
"""

核心代码:

import cv2

data_path = 'videos/'
fps = 30 #0.03333s fps=20 0.05s
size = (160, 210)
video = cv2.VideoWriter(f"{data_path+"breakout"}.avi", cv2.VideoWriter_fourcc(*'XVID'), fps, size) # 记录画面帧
img = env.ale.getScreenRGB()[:, :, ::-1]
video.write(img) video.release()

实现了将30帧画面压到一秒视频的方式来收集所有画面帧,最后得到的一个avi的视频。

从  atari_env.py  模块中可以看到不使用gym模块而直接使用atari_py模块进行操作的方式:

我们知道gym库在进行atari游戏仿真时其底层用的就atari_py库,换句话说gym相当于在atari_py库的基础上进行了包装,那么我们也是可以跨过gym库直接调用atari_py库的。

import atari_py

ale = atari_py.ALEInterface()
ale.loadROM(atari_py.get_game_path(args.game)) ale.setInt('random_seed', args.seed)
ale.setInt('max_num_frames_per_episode',args.max_episode_length)
ale.setFloat('repeat_action_probability', 0) # 可变更的地方 actions = ale.getMinimalActionSet()

生成游戏环境对象:

ale = atari_py.ALEInterface()

加载游戏环境的ROM文件:

ale.loadROM(atari_py.get_game_path(args.game))

可以设置为:

ale.loadROM(atari_py.get_game_path("breakout"))

设置环境的随机种子:

ale.setInt('random_seed', args.seed)

设置游戏一个episode内最多的帧数,这里的episode是指多个lives条件下的整个episode。

ale.setInt('max_num_frames_per_episode',args.max_episode_length)

设置仿真环境是否重复上一次的输入动作的概率:(如果该值不为0,那么仿真环境会以该概率重复上次的输入动作而忽略掉本次的动作输入)

ale.setFloat('repeat_action_probability', 0)

获取游戏环境的动作最小集合:

actions = ale.getMinimalActionSet()

打印当前环境下可以价值ROM的游戏集合:

atari_py.list_games()

['tetris', 'lost_luggage', 'pitfall2', 'pong', 'koolaid', 'breakout', 'hero', 'jamesbond', 'alien', 'road_runner', 'tennis', 'beam_rider', 'entombed', 'freeway', 'double_dunk', 'seaquest', 'king_kong', 'backgammon', 'casino', 'tic_tac_toe_3d', 'mr_do', 'zaxxon', 'ice_hockey', 'frogger', 'gravitar', 'private_eye', 'centipede', 'video_cube', 'adventure', 'defender', 'combat', 'star_gunner', 'flag_capture', 'othello', 'donkey_kong', 'et', 'air_raid', 'battle_zone', 'haunted_house', 'bank_heist', 'klax', 'up_n_down', 'pooyan', 'fishing_derby', 'darkchambers', 'kangaroo', 'warlords', 'berzerk', 'kung_fu_master', 'earthworld', 'demon_attack', 'superman', 'venture', 'tutankham', 'enduro', 'yars_revenge', 'joust', 'robotank', 'journey_escape', 'time_pilot', 'atlantis', 'pitfall', 'video_chess', 'atlantis2', 'basic_math', 'crossbow', 'word_zapper', 'mario_bros', 'sir_lancelot', '__init__', 'hangman', 'laser_gates', 'asterix', 'carnival', 'turmoil', 'keystone_kapers', 'surround', 'amidar', 'krull', 'pacman', 'phoenix', 'qbert', 'space_invaders', 'riverraid', 'skiing', 'ms_pacman', 'kaboom', 'solaris', 'maze_craze', 'human_cannonball', 'blackjack', 'frostbite', 'space_war', 'boxing', 'name_this_game', 'gopher', 'elevator_action', 'crazy_climber', 'asteroids', 'video_pinball', 'assault', 'bowling', 'montezuma_revenge', 'trondead', 'wizard_of_wor', 'video_checkers', 'galaxian', 'miniature_golf', 'chopper_command']

==============================================

DQN2013代码尝试复现版(存在各种实现问题及Bug,个人尝试复现版,没有follow价值)的更多相关文章

  1. 【CC2530入门教程-增强版】基础技能综合实训案例(基础版)-上位机源码

    [CC2530入门教程-增强版]基础技能综合实训案例(基础版)-上位机源码 广东职业技术学院  欧浩源 一.需求分析 按照指定参数打开串口,与测控终端建立数据传输通道,并根据应用要求实现程序逻辑,具体 ...

  2. 1个多商户、多平台版 微信小程序(多商户、多平台版),影城行业、影业连锁 多商户、多平台版微信小程序。(基于多平台版,支持在业务上 可给 每个单独影城 分发定制单独的小程序版本)

    1个 影城行业 微信小程序(多商户.多平台版), 影业连锁 多商户.多平台版微信小程序.(基于多平台版,支持在业务上 可给 每个单独影城 分发定制单独的小程序版本) 资讯QQ: 876635409  ...

  3. HTML与CSS入门经典(第9版)试读 附随书源码 pdf扫描版​

    HTML与CSS入门经典(第9版)是经典畅销图书<HTML与CSS入门经典>的最新版本,与过去的版本相同,本书采用直观.循序渐进的方法,为读者讲解使用HTML5与CSS3设计.创建并维护世 ...

  4. 用nopcomerce3.8版本的同行注意了,前2天发布3.8正式版后,作者收到一些BuG,作者修复后重新提供了一个源代码包下载.

    用nopcomerce3.8版本的同行注意了,前2天发布3.8正式版后,作者收到一些BuG,作者修复后重新提供了一个源代码包下载地址,不是github上的那个链接.去作者官网论坛我那个链接地址,或关注 ...

  5. 劣质代码评析——《写给大家看的C语言书(第2版)》附录B之21点程序(八)

    [重构](续) 牌的表示: 一副牌有52张,可用一整数数组描述.但是由于在游戏过程中牌数在不断减少,所以用一表示剩余张数的整数和一整数数组共同描述.C99支持一种变量长度数组,但用在这里并没有什么特别 ...

  6. 海王星给你好看!FineUI v4.0公测版发布暨《你找BUG我送书》活动开始(活动已结束!)

    <FineUI v4.0 你找BUG我送书>活动已结束,恭喜如下三位网友获得由 FineUI 作者亲自翻译的图书<jQuery实战 第二版>! 奋斗~ 吉吉﹑ purplebo ...

  7. 写代码的心得,怎么减少编程中的 bug?

    遭遇 bug 的时候,理性的程序员会说:这个 bug 能复现吗? 自负型:这不可能,在我这是好好的. 经验型:不应该,以前怎么没问题? 幻想型:可能是数据有问题. 无辜型:我好几个星期都没碰这块代码了 ...

  8. 【漏洞复现】MSF添加ms17-010的exp脚本及攻击复现

    原文地址:https://bbs.ichunqiu.com/thread-23115-1-1.html 本来今晚在准备复现最近的CVE-2017-11882,由于本人是小白一枚,不知道这么添加msf的 ...

  9. vs.net 2005 C# WinForm GroupBOX 的BUG?尝试读取或写入受保护的内存。这通常指示其他内存已损坏

    其实很久没有写程序了,国庆难得有空闲,写了个游戏辅助机器人,程序写好能用后本想把UI控件放到GroupBox里归下分类,美化下界面,结果一运行报“尝试读取或写入受保护的内存.这通常指示其他内存已损坏” ...

  10. JLink v8克隆版破解向导(此方法仅适用XP32位版 WIN7及以上和64位均不支持 建议使用虚拟机)

    此方法仅适用XP32位版 WIN7及以上和64位均不支持 建议使用虚拟机 摘要 Jlink 4.5版本之后驱动会识别老的克隆版的JlinkV8,Jlink软件在启动时会提示为克隆版本后退出.目前主流的 ...

随机推荐

  1. 内部网关协议RIP-路由选择协议

    路由信息协议RIP(Routing Information Protocol)是内部网关协议IGP中最先得到广泛使用的协议,其相关标准文档为RFC1058. 一.RIP基本工作原理 RIP要求自治系统 ...

  2. nordic——long range测试

    简介:本案例测试了long range,注意nrf52系列芯片中,部分硬件是不支持CADE的,也就是不支持long range,如nrf52832就不支持long range.同时协议栈也是部分支持, ...

  3. Mysql行转列,列转行 WITH ROLLUP 统计

    Mysql行转列,列转行 WITH ROLLUP 统计 DROP TABLE IF EXISTS tb_score; CREATE TABLE tb_score( id INT(11) NOT NUL ...

  4. OpenCV + sklearnSVM 实现手写数字分割和识别

    这学期机器学习考核方式以大作业的形式进行考核,而且只能使用一些传统的机器学习算法. 综合再三,选择了自己比较熟悉的MNIST数据集以及OpenCV来完成手写数字的分割和识别作为大作业. 1. 数据集准 ...

  5. 【路径规划】OSQP曲线平滑 公式及代码

    参考与前言 apollo 代码:https://github.com/ApolloAuto/apollo/tree/master/modules/planning/math/smoothing_spl ...

  6. .NET App 与Windows系统媒体控制(SMTC)交互

    当你使用Edge等浏览器或系统软件播放媒体时,Windows控制中心就会出现相应的媒体信息以及控制播放的功能,如图. SMTC (SystemMediaTransportControls) 是一个Wi ...

  7. 使用VS Code 学习算法(第四版)

    最近在学习算法(第四版),书中一直在使用命令行来执行Java程序,而使用Eclipse时,很难使用命令行,或者说我根本就不会用,于是就想研究一下使用VS Code来编写代码,使用命令行来执行程序.看了 ...

  8. Docker开启远程安全访问

    一.编辑docker.service文件 vi /usr/lib/systemd/system/docker.service 找到 [Service] 节点,修改 ExecStart 属性,增加 -H ...

  9. redis出现错误提示MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for......

    某天,redis出现了这样一个错误提示: MISCONF Redis is configured to save RDB snapshots, but is currently not able to ...

  10. Java的TimeStamp

    Java的TimeStamp 很简单,我们可以这样声明 Timestamp ts=new Timestamp(new Date().getTime());这样我们就可以得到时间比较具体的一个类型转换! ...