使用matplotlib_inline和torch、d2l显示错误:NotImplementedError: Implementenable_gui in a subclass

问题描述 投票:0回答:1

我学习“深入学习”pytorch版本,在https://d2l.ai/chapter_preliminaries/calculus.html,我使用了“jupyter笔记本”命令,并在jupyter中运行了pytorch代码,一切运行正常,我将pytorch代码重写成了1.py,这样可以方便的调试pytorch代码,这里是我的1.py代码


#%matplotlib inline
import os
import numpy as np
from matplotlib_inline import backend_inline
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)'])


我运行命令 “conda 激活 d2l” 然后运行 “蟒蛇1.py” 它显示错误:


⇒  conda activate d2l
lee@Princekin-MacbookPro:~/Desktop/Artificial_Intelligence/DEEP_LEARNING/DIVE_INTO_DEEP_LEARNING_PyTorch/task/2.4|main⚡
⇒  python 1.py
h=0.10000, numerical limit=2.30000
h=0.01000, numerical limit=2.03000
h=0.00100, numerical limit=2.00300
h=0.00010, numerical limit=2.00030
h=0.00001, numerical limit=2.00003
Traceback (most recent call last):
  File "/Users/lee/Desktop/Artificial_Intelligence/DEEP_LEARNING/DIVE_INTO_DEEP_LEARNING_PyTorch/task/2.4/1.py", line 79, in <module>
    plot(x, [f(x), 2 * x - 3], 'x', 'f(x)', legend=['f(x)', 'Tangent line (x=1)'])
  File "/Users/lee/Desktop/Artificial_Intelligence/DEEP_LEARNING/DIVE_INTO_DEEP_LEARNING_PyTorch/task/2.4/1.py", line 54, in plot
    axes = axes if axes else d2l.plt.gca()
  File "/Users/lee/miniconda3/envs/d2l/lib/python3.9/site-packages/matplotlib/pyplot.py", line 2309, in gca
    return gcf().gca()
  File "/Users/lee/miniconda3/envs/d2l/lib/python3.9/site-packages/matplotlib/pyplot.py", line 906, in gcf
    return figure()
  File "/Users/lee/miniconda3/envs/d2l/lib/python3.9/site-packages/matplotlib/_api/deprecation.py", line 454, in wrapper
    return func(*args, **kwargs)
  File "/Users/lee/miniconda3/envs/d2l/lib/python3.9/site-packages/matplotlib/pyplot.py", line 840, in figure
    manager = new_figure_manager(
  File "/Users/lee/miniconda3/envs/d2l/lib/python3.9/site-packages/matplotlib/pyplot.py", line 383, in new_figure_manager
    _warn_if_gui_out_of_main_thread()
  File "/Users/lee/miniconda3/envs/d2l/lib/python3.9/site-packages/matplotlib/pyplot.py", line 361, in _warn_if_gui_out_of_main_thread
    if _get_required_interactive_framework(_get_backend_mod()):
  File "/Users/lee/miniconda3/envs/d2l/lib/python3.9/site-packages/matplotlib/pyplot.py", line 208, in _get_backend_mod
    switch_backend(rcParams._get("backend"))
  File "/Users/lee/miniconda3/envs/d2l/lib/python3.9/site-packages/matplotlib/pyplot.py", line 356, in switch_backend
    install_repl_displayhook()
  File "/Users/lee/miniconda3/envs/d2l/lib/python3.9/site-packages/matplotlib/pyplot.py", line 157, in install_repl_displayhook
    ip.enable_gui(ipython_gui_name)
  File "/Users/lee/miniconda3/envs/d2l/lib/python3.9/site-packages/IPython/core/interactiveshell.py", line 3607, in enable_gui
    raise NotImplementedError('Implement enable_gui in a subclass')
NotImplementedError: Implement enable_gui in a subclass
lee@Princekin-MacbookPro:~/Desktop/Artificial_Intelligence/DEEP_LEARNING/DIVE_INTO_DEEP_LEARNING_PyTorch/task/2.4|main⚡
⇒

我不知道如何解决这个问题,如果您有任何想法,我们将不胜感激,谢谢

matplotlib deep-learning pytorch d2l
1个回答
0
投票

经过多次尝试,我找到了解决方案,

  1. 更改1.py

#%matplotlib inline
import os
import numpy as np
from matplotlib_inline import backend_inline
from d2l import torch as d2l
import matplotlib.pyplot as plt


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)'])


plt.show()


  1. 运行命令“IPython 1.py”;

然后就成功了,并展示了图,希望对大家有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.