プリンキピア

第2章準備

2.4.2. Visualization Utilities2.4.2 可視化のための道具

We can visualize the slopes of functions using the matplotlib library. We need to define a few functions. As its name indicates, use_svg_display tells matplotlib to output graphics in SVG format for crisper images. The comment #@save is a special modifier that allows us to save any function, class, or other code block to the d2l package so that we can invoke it later without repeating the code, e.g., via d2l.use_svg_display().
英語のヒント
matplotlibライブラリを使えば、関数の傾きを可視化できる。いくつかの関数を定義する必要がある。その名のとおり、use_svg_displayは、よりくっきりした画像のために、SVG形式でグラフを出力するようmatplotlibに指示する。コメント#@saveは特別な修飾子で、関数やクラスなどのコードのブロックをd2lパッケージに保存できるようにする。そうすれば、コードを繰り返さずに、たとえばd2l.use_svg_display()のように後から呼び出せる。
def use_svg_display():  #@save
    """Use the svg format to display a plot in Jupyter."""
    backend_inline.set_matplotlib_formats('svg')
Conveniently, we can set figure sizes with set_figsize. Since the import statement from matplotlib import pyplot as plt was marked via #@save in the d2l package, we can call d2l.plt.
英語のヒント
便利なことに、set_figsizeで図の大きさを設定できる。import文from matplotlib import pyplot as pltはd2lパッケージで#@saveの印が付けられているので、d2l.pltを呼び出せる。
def set_figsize(figsize=(3.5, 2.5)):  #@save
    """Set the figure size for matplotlib."""
    use_svg_display()
    d2l.plt.rcParams['figure.figsize'] = figsize
The set_axes function can associate axes with properties, including labels, ranges, and scales.
英語のヒント
set_axes関数は、軸に、ラベル、範囲、目盛りといった性質を結びつけられる。
#@save
def set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend):
    """Set the axes for 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()
With these three functions, we can define a plot function to overlay multiple curves. Much of the code here is just ensuring that the sizes and shapes of inputs match.
英語のヒント
これら三つの関数を使って、複数の曲線を重ねて描くplot関数を定義できる。ここでのコードの多くは、入力の大きさと形状が合っていることを確かめているだけである。
#@save
def plot(X, Y=None, xlabel=None, ylabel=None, legend=[], xlim=None,
         ylim=None, xscale='linear', yscale='linear',
         fmts=('-', 'm--', 'g-.', 'r:'), figsize=(3.5, 2.5), axes=None):
    """Plot data points."""

    def has_one_axis(X):  # True if X (tensor or list) has 1 axis
        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)

    set_figsize(figsize)
    if axes is None:
        axes = d2l.plt.gca()
    axes.cla()
    for x, y, fmt in zip(X, Y, fmts):
        axes.plot(x,y,fmt) if len(x) else axes.plot(y,fmt)
    set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend)
Now we can plot the function u=f(x) and its tangent line y=2x−3 at x=1, where the coefficient 2 is the slope of the tangent line.
英語のヒント
これで、関数u=f(x)と、x=1でのその接線y=2x−3を描ける。ここで係数2は接線の傾きである。
x = np.arange(0, 3, 0.1)
plot(x, [f(x), 2 * x - 3], 'x', 'f(x)', legend=['f(x)', 'Tangent line (x=1)'])