机器学习深度学习【免费下载链接】dopamineDopamine is a research framework for fast prototyping of reinforcement learning algorithms.项目地址https://gitcode.com/gh_mirrors/do/dopamine点击查看免费下载导读本文围绕 Dopamine 强化学习研究框架中dopamine.utils.bar_plotter模块展开系统讲解BarPlotter类如何将 Agent 回调产生的数据如 Rainbow 等分布型算法的 Return 分布绘制为柱状图并经 pygame 表面变换后交给AgentVisualizer拼合成可视化帧乃至视频。读完本文你将掌握BarPlotter的数据契约、全部可配置参数、底层绘制原理以及如何在自己的实验中复用这套可视化组件。BarPlotter 模块定位与设计意图BarPlotter是 Dopamine 可视化工具链dopamine/utils中负责柱状图的 Plotter 组件官方文档对其定位只有一句话BarPlotter used for drawing bar plots用于绘制柱状图的 Plotter对应源码位于 dopamine/utils/bar_plotter.py。它在框架中的角色需要结合可视化工具链的整体结构来理解。Dopamine 的dopamine/utils目录下共提供四类 Plotter各自负责一种可视元素Plotter 组件用途AtariPlotter渲染 Atari 2600 游戏原始帧LinePlotter绘制折线图奖励曲线、Q 值曲线等BarPlotter绘制柱状图Return 分布、动作概率分布等AgentVisualizer非 Plotter负责把多个 Plotter 的输出拼合成帧并生成视频BarPlotter直接继承自抽象基类 dopamine/utils/plotter.py 中的Plotter官方类文档见 Plotter.md并标注了gin.configurable装饰器——这意味着它的构造参数也可以被 gin 配置系统解析覆盖。需要特别说明文档中强调的一个副作用实例化BarPlotter会修改全局 matplotlib 字体设置源码第 79 行执行matplotlib.rc(font, **self.parameters[font])。如果你的代码其他部分也依赖 matplotlib 的默认字体这是需要留意的全局影响。数据契约get_bar_data_fn 回调BarPlotter与外部世界唯一的接口是一个回调函数get_bar_data_fn。在构造函数__init__中第一行断言就是assert get_bar_data_fn in self.parameters也就是说get_bar_data_fn是必须提供的参数缺了它构造会直接失败。该回调的职责在源码 docstring 中有明确约定期望一个可调用的get_bar_data_fn参数它将为每个动作返回一组分布a list of distributions for each of the actions。通常这将是来自 Agent 的回调返回关于其性能的有用信息。在实际绘制时draw()方法返回的数据被当作二维数组解包bar_data self.parameters[get_bar_data_fn]() num_actions, num_bins bar_data.shape可见数据形状必须满足行数num_actions每个动作一行即图中一组柱子列数num_bins每行数据的长度即柱状图的 x 轴分箱数。框架中最典型的真实案例来自 dopamine/utils/example_viz_lib.py。其中的MyRainbowAgent通过子类化RainbowAgent暴露了一个get_probabilities()方法把网络输出的动作概率分布直接作为柱状图数据def get_probabilities(self): return self._sess.run( tf.squeeze(self._net_outputs.probabilities), {self.state_ph: self.state} )然后在MyRunner.visualize()中为 Rainbow 类型的 Agent 构造BarPlotter并绑定该回调example_viz_lib.py第 211-216 行q_params[xlabel] Return q_params[ylabel] Return probability q_params[title] Return distribution q_params[get_bar_data_fn] self._agent.get_probabilities q_plot bar_plotter.BarPlotter(parameter_dictq_params)这就是BarPlotter的典型应用场景把分布型强化学习算法如 C51、Rainbow、IQN 等学到的 Return 分布或动作概率分布可视化为逐帧刷新的柱状图。对比之下DQNQ 值与 IQN分位数 Q 值在同一个visualize()方法中走的是LinePlotter分支只有分布类算法走BarPlotter分支。参数体系全部默认值与取值建议BarPlotter的全部默认参数定义在类属性_defaults中bar_plotter.py第 42-58 行下面是完整清单及其作用参数默认值含义与说明x0该 Plotter 输出在合成画面中的 x 坐标由基类保证始终存在y0该 Plotter 输出在合成画面中的 y 坐标width213最终输出 surface 的宽度pygame 平滑缩放目标宽度height210最终输出 surface 的高度fontsize30坐标轴刻度字号xlabel/ylabel用fontsize - 2title用fontsize 2bg_color#f8f7f2绘图区axes背景色浅米色face_color#ffffff整个 figure 画布背景色白色colors[b,g,r,c,m,y,k,w]每根柱子每个动作的循环配色i % num_colors索引max_width500折线图用参数柱状图不消费继承自共用默认模板figsize(12, 9)matplotlib figure 尺寸英寸先按此渲染再缩放font{family: Bitstream Vera Sans, weight: regular, size: 26}写入matplotlib.rc(font, ...)的全局字体设置除_defaults外draw()还会消费两个可选键legend若存在于参数中则作为图例标签列表传给self.plot.legend(self.parameters[legend])。在example_viz_lib.py中它被设为[Action 0, Action 1, ...]按num_actions生成。xlabel/ylabel/title由基类_setup_plot()消费用于设置坐标轴与标题文字。参数合并的顺序逻辑在基类 dopamine/utils/plotter.py 第 49-51 行self.parameters {x: 0, y: 0} self.parameters.update(self._defaults) self.parameters.update(parameter_dict)即内置x/y默认值 → 子类_defaults→ 用户传入的parameter_dict三级覆盖后传入的优先级最高。绘制原理matplotlib 渲染 pygame 表面搬运draw()是BarPlotter的核心方法官方文档描述为绘制柱状图若parameter_dict含legend键则用作图例返回待AgentVisualizer渲染的对象。其内部流程可以分为三个阶段bar_plotter.py第 81-112 行阶段一matplotlib 出图。调用基类_setup_plot()完成画布清理与样式设置清空当前坐标轴、设置 figure/axes 背景色、可选地设置 x/y 轴标签、标题、刻度及其字号随后按num_actions逐行绘制self._setup_plot() num_colors len(self.parameters[colors]) bar_data self.parameters[get_bar_data_fn]() num_actions, num_bins bar_data.shape for i in range(num_actions): self.plot.bar( np.arange(num_bins), bar_data[i], colorself.parameters[colors][i % num_colors], )x 轴固定为np.arange(num_bins)0 到 bins-1 的整数刻度每个动作一组同色柱子颜色按i % num_colors循环取用因此动作数超过 8 时会复用颜色。阶段二把 matplotlib 画布拷贝进 pygame surface。关键代码如下self.fig.canvas.draw() width, height self.fig.canvas.get_width_height() if self.plot_surface is None: self.plot_surface pygame.Surface((width, height)) plot_buffer np.frombuffer(self.fig.canvas.buffer_rgba(), np.uint32) surf_buffer np.frombuffer(self.plot_surface.get_buffer(), dtypenp.int32) np.copyto(surf_buffer, plot_buffer)这里没有走 matplotlib 保存图片文件再加载的慢路径而是直接用numpy.frombuffer把 matplotlib 画布的 RGBA 像素缓冲复制到 pygame surface 的像素缓冲中实现内存级零拷贝搬运。阶段三缩放返回。用pygame.transform.smoothscale把大尺寸渲染结果缩放到配置的width×height默认 213×210返回供AgentVisualizer.blit的 surface 对象。在 AgentVisualizer 中的集成与整段渲染管线BarPlotter单独没有意义它必须与 dopamine/utils/agent_visualizer.py 中的AgentVisualizer配合。完整渲染管线如下采样阶段Agent 与环境交互step/_select_action回调如get_probabilities从当前状态收集数据绘制阶段AgentVisualizer.visualize()遍历plotters列表逐个调用plotter.draw()得到 pygame surface并按(plotter.x, plotter.y)坐标blit到合成画面落盘阶段save_frame()把画面像素拆成 RGB 三通道存为 PNG 帧成片阶段generate_video()调用ffmpeg-r 30 -vcodec libx264 -crf 25把帧序列合成 mp4。example_viz_lib.py中MyRunner.visualize()展示了完整的四元素布局第 217-233 行screen_width ( atari_plot.parameters[width] reward_plot.parameters[width] ) screen_height ( atari_plot.parameters[height] q_plot.parameters[height] ) # Dimensions need to be divisible by 2: if screen_width % 2 0: screen_width 1 if screen_height % 2 0: screen_height 1 visualizer agent_visualizer.AgentVisualizer( record_pathrecord_path, plotters[atari_plot, reward_plot, q_plot], screen_widthscreen_width, screen_heightscreen_height, )其中BarPlotter的坐标被设置为x atari_plot.parameters[width] // 2、y atari_plot.parameters[height]即游戏画面右上角reward 折线图在其左侧游戏画面位于左上整幅画面呈现 2×2 信息布局。注意代码中会对宽高做奇偶修正因为部分绘制路径要求尺寸可被 2 整除。实战复用一个自定义 BarPlotter基于上述契约你可以非常轻量地构造自己的BarPlotter。下面给出一个最小可运行示例独立于框架的 Atari 环境用随机数据模拟每个动作的分布import numpy as np from dopamine.utils.bar_plotter import BarPlotter num_actions 4 num_bins 51 # 对应 C51 的 51 个分位 bin def get_bar_data_fn(): # 返回 shape (num_actions, num_bins) 的数组 data np.random.rand(num_actions, num_bins) return data / data.sum(axis1, keepdimsTrue) # 归一化为概率 plotter BarPlotter(parameter_dict{ x: 160, y: 0, # 放在合成画面右侧 width: 213, height: 210, # 输出 surface 尺寸 fontsize: 24, bg_color: #f8f7f2, face_color: #ffffff, xlabel: Return, ylabel: Return probability, title: Return distribution, legend: [fAction {i} for i in range(num_actions)], get_bar_data_fn: get_bar_data_fn, }) surface plotter.draw() # 返回 pygame.Surface若要在完整管线中运行官方示例可参考 dopamine/utils/example_viz.py 的命令行入口其功能是加载已训练 checkpoint在 eval 模式下边回放游戏边生成可视化视频python example_viz.py \ --agentrainbow \ --gameSpaceInvaders \ --num_steps1000 \ --root_dir/tmp/dopamine \ --restore_checkpoint/path/to/checkpoint/tf_ckpt-199其余可用 flag 包括--use_legacy_checkpoint加载旧版 Keras 前 checkpoint 时置为True。主入口run()example_viz_lib.py第 278-300 行还会动态解析一段 gin 配置设置游戏名与WrappedReplayBuffer.replay_capacity 300再依次创建 Runner、执行visualize()生成图像与视频。其中 Rainbow 分支的 Return 分布图即由本文主角BarPlotter负责绘制。使用注意事项matplotlib 字体副作用构造BarPlotter即执行matplotlib.rc(font, ...)会全局改变 matplotlib 字体。文档与源码均提示如果代码中其他部分还要用 matplotlib请评估影响。pygame 环境依赖AgentVisualizer构造时会设置os.environ[SDL_VIDEODRIVER] dummy并pygame.init()以避免无显示环境下报pygame.error: No available video deviceBarPlotter本身也依赖pygame.Surface因此运行环境需要安装 pygame。数据形状约束get_bar_data_fn必须返回可解包为(num_actions, num_bins)的二维数组否则draw()会因bar_data.shape解包失败而抛错。颜色循环默认仅 8 种颜色b/g/r/c/m/y/k/w动作数超过 8 时颜色会重复必要时可通过colors参数传入自定义调色板。视频生成generate_video()内部通过subprocess.call调用ffmpeg源码注释明确提示仅应在可信路径下使用此功能。延伸阅读模块级 API 文档dopamine.utils.bar_plotter 与类文档 BarPlotter基类与参数合并逻辑dopamine/utils/plotter.py、Plotter.md整条可视化管线的组合器dopamine/utils/agent_visualizer.py、AgentVisualizer.md官方示例含 Rainbow Return 分布的可视化编排dopamine/utils/example_viz_lib.py、dopamine/utils/example_viz.py同类组件对比dopamine/utils/line_plotter.py、dopamine/utils/atari_plotter.py可视化实验入口Jupyter Notebook 方式dopamine/colab/agent_visualizer.ipynb赞分享机器学习深度学习【免费下载链接】dopamineDopamine is a research framework for fast prototyping of reinforcement learning algorithms.项目地址https://gitcode.com/gh_mirrors/do/dopamine点击查看免费下载相关推荐在 Apple Silicon 上运行 Omarchy 4.0.1基于 Lume ARM64 VM、Arch Linux ARM 与 Rosetta 的兼容性移植实战在 Apple Silicon 上运行 Omarchy 4.0.1基于 Lume ARM64 VM、Arch Linux ARM 与 Rosetta 的兼容性机器学习深度学习Dopamine Plotter 可视化基类解析从抽象基类到强化学习智能体行为绘图Dopamine Plotter 可视化基类解析从抽象基类到强化学习智能体行为绘图 Dopamine 是面向强化学习算法快速原型设计的研究框架在其 dopa机器学习深度学习CKIP Transformers vs 其他中文NLP工具性能对比与选择指南CKIP Transformers vs 其他中文NLP工具性能对比与选择指南 CKIP Transformers是一款基于Transformer架构的中文自上一篇大麦自动抢票脚本实操指南:3 条命令跑通从搜索到下单的全流程下一篇OpenProject 11.3.0 发布解读GitHub 集成、API v3 扩展与新成员邀请流程创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考