将D2L PyTorch代码转为.py运行时触发enable_gui子类实现错误求助
问题解决:Python脚本运行D2L绘图代码触发
NotImplementedError 问题场景
学习《DIVE INTO DEEP LEARNING》PyTorch版本时,Jupyter Notebook中运行微积分章节代码一切正常,但将代码改写为.py脚本后,执行conda activate d2l再运行python 1.py,数值计算输出正常,绘图时触发以下错误:
NotImplementedError: Implement enable_gui in a subclass
报错原因
原代码依赖matplotlib_inline.backend_inline这个Jupyter专用的绘图后端,在普通Python脚本环境中,matplotlib无法找到合适的GUI交互框架,尝试调用IPython的GUI功能时失败,从而抛出该错误。
解决方案
方案1:保存图片而非交互式显示(无GUI环境通用)
这种方式适合服务器或无桌面环境的场景,生成图片文件而非弹出窗口:
- 在代码开头添加非交互式后端配置:
import matplotlib matplotlib.use('Agg') # 指定非交互式后端,用于生成图片文件
- 注释掉针对Jupyter的
use_svg_display函数及调用(该函数仅在Notebook环境生效):
# def use_svg_display(): #@save # """使用svg格式在Jupyter中显示绘图""" # backend_inline.set_matplotlib_formats('svg') def set_figsize(figsize=(3.5, 2.5)): #@save """设置matplotlib的图表大小""" # use_svg_display() # 注释掉该行 d2l.plt.rcParams['figure.figsize'] = figsize
- 在脚本最后添加保存图片的代码:
d2l.plt.savefig('calculus_plot.png')
运行脚本后,当前目录会生成calculus_plot.png图片文件。
方案2:启用系统支持的GUI后端(需本地有桌面环境)
根据操作系统指定对应的GUI后端,让脚本弹出窗口显示图表:
- MacOS系统,在代码开头添加:
import matplotlib matplotlib.use('macosx')
- Linux系统,在代码开头添加:
import matplotlib matplotlib.use('TkAgg')
- Windows系统,在代码开头添加:
import matplotlib matplotlib.use('QtAgg')
修改后运行脚本,会自动弹出窗口显示绘制的图表。
完整修改后的示例代码
import matplotlib matplotlib.use('Agg') # 可根据需求替换为macosx/TkAgg/QtAgg import os import numpy as np # from matplotlib_inline import backend_inline # 注释掉Jupyter专用模块 from d2l import torch as d2l def f(x): return 3 * x ** 2 - 4 * x def numerical_lim(f, x, h): return (f(x + h) - f(x)) / h h = 0.1 for i in range(5): print(f'h={h:.5f}, numerical limit={numerical_lim(f, 1, h):.5f}') h *= 0.1 # def use_svg_display(): #@save # """使用svg格式在Jupyter中显示绘图""" # backend_inline.set_matplotlib_formats('svg') def set_figsize(figsize=(3.5, 2.5)): #@save """设置matplotlib的图表大小""" # use_svg_display() d2l.plt.rcParams['figure.figsize'] = figsize #@save def set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend): """设置matplotlib的轴""" axes.set_xlabel(xlabel) axes.set_ylabel(ylabel) axes.set_xscale(xscale) axes.set_yscale(yscale) axes.set_xlim(xlim) axes.set_ylim(ylim) if legend: axes.legend(legend) axes.grid() #@save def plot(X, Y=None, xlabel=None, ylabel=None, legend=None, xlim=None, ylim=None, xscale='linear', yscale='linear', fmts=('-', 'm--', 'g-.', 'r:'), figsize=(3.5, 2.5), axes=None): """绘制数据点""" if legend is None: legend = [] set_figsize(figsize) axes = axes if axes else d2l.plt.gca() # 如果X有一个轴,输出True def has_one_axis(X): return (hasattr(X, "ndim") and X.ndim == 1 or isinstance(X, list) and not hasattr(X[0], "__len__")) if has_one_axis(X): X = [X] if Y is None: X, Y = [[]] * len(X), X elif has_one_axis(Y): Y = [Y] if len(X) != len(Y): X = X * len(Y) axes.cla() for x, y, fmt in zip(X, Y, fmts): if len(x): axes.plot(x, y, fmt) else: axes.plot(y, fmt) set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend) x = np.arange(0, 3, 0.1) plot(x, [f(x), 2 * x - 3], 'x', 'f(x)', legend=['f(x)', 'Tangent line (x=1)']) d2l.plt.savefig('calculus_plot.png') # 保存图片(方案1需保留,方案2可删除)
内容的提问来源于stack exchange,提问作者Princekin
相关产品推荐
相关产品推荐

