绘制函数 y=f(x)=x^3−1/x 和其在 x=1 处切线的图像

绘制函数 y=f(x)=x^3−1/x 和其在 x=1 处切线的图像。

%matplotlib inline
import numpy as np
from IPython import display
from d2l import torch as d2l


def f(x):
    return x ** 3 - 1 / x

use_svg_display函数指定matplotlib软件包输出svg图表以获得更清晰的图像

def use_svg_display():  #@save
    """使用svg格式在Jupyter中显示绘图。"""
    display.set_matplotlib_formats('svg')

定义set_figsize函数来设置图表大小

def set_figsize(figsize=(3.5, 2.5)):  #@save

  """设置matplotlib的图表大小。"""

  use_svg_display()

  d2l.plt.rcParams['figure.figsize'] = figsize

set_axes函数用于设置由matplotlib生成图表的轴的属性

#@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), 4 * x - 4], 'x', 'f(x)', legend=['f(x)', 'Tangent line (x=1)'])

绘制函数 y=f(x)=x^3−1/x 和其在 x=1 处切线的图像_第1张图片

你可能感兴趣的:(深度学习,深度学习,随机梯度下降,python)