pytorch 深度学习之微积分

导数和微分

如果的 \(f\) 导数存在,这个极限被定义为:

\[f^{\prime}(x)=\lim _{h \rightarrow 0} \frac{f(x+h)-f(x)}{h} \]

如果 \(f^{\prime}(a)\) 存在,则称 \(f\)\(a\) 处是可微(differentiable)的。 如果 \(f\) 在一个区间内的每个数上都是可微的,则此函数在此区间中是可微的。导数 \(f^{\prime}(x)\) 解释为 \(f(x)\) 相对于 \(x\) 的瞬时(instantaneous)变化率。 所谓的瞬时变化率是基于 \(x\) 中的变化 \(h\),且 \(h\) 接近 0。

举例:\(u=f(x)=3 x^{2}-4 x\)

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

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

导数的几个等价符号:

\[f^{\prime}(x)=y^{\prime}=\frac{d y}{d x}=\frac{d f}{d x}=\frac{d}{d x} f(x)=D f(x)=D_{x} f(x) \]

常见函数求微分:

  • \(D C=0 ( C\) 是一个常数 \()\)
  • \(D x^{n}=n x^{n-1}\) (幂律 (power rule) , \(n\) 是任意实数)
  • \(D e^{x}=e^{x}\)
  • \(D \ln (x)=1 / x\)

常用法则:

  • 常数相乘法则:

    \[\frac{d}{d x}[C f(x)]=C \frac{d}{d x} f(x) \]

  • 加法法则:

    \[\frac{d}{d x}[f(x)+g(x)]=\frac{d}{d x} f(x)+\frac{d}{d x} g(x) \]

  • 乘法法则:

    \[\frac{d}{d x}[f(x) g(x)]=f(x) \frac{d}{d x}[g(x)]+g(x) \frac{d}{d x}[f(x)] \]

  • 除法法则:

    \[\frac{d}{{dx}}\left[ {\frac{{f(x)}}{{g(x)}}} \right] = \frac{{g(x)\frac{d}{{dx}}\left[ {f(x)} \right] - f(x)\frac{d}{{dx}}\left[ {g(x)} \right]}}{{{{\left[ {g(x)} \right]}^2}}} \]

%matplotlib inline
import numpy as np
from IPython import display
from matplotlib import pyplot as plt

def use_svg_display():
    display.set_matplotlib_formats('svg')

def set_figsize(figsize=(3.5, 2.5)):
    use_svg_display()
    plt.rcParams['figure.figsize'] = figsize

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()

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 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)'])
C:\Users\Administrator\AppData\Local\Temp\ipykernel_9800\3988637146.py:7: DeprecationWarning: `set_matplotlib_formats` is deprecated since IPython 7.23, directly use `matplotlib_inline.backend_inline.set_matplotlib_formats()`
  display.set_matplotlib_formats('svg')

偏导数

\(y = f({x_1},{x_2},...{x_n})\) 是一个具有 \(n\) 个变量的函数,\(y\) 关于第 \(i\) 个参数 \(x_n\) 的偏导数为:

\[\frac{{\partial y}}{{\partial {x_i}}} = \mathop {\lim }\limits_{h \to 0} \frac{{f({x_1},...{x_{i - 1}},{x_i} + h,{x_{i + 1}},...{x_n}) - f({x_1},...{x_i},...,{x_n})}}{h} \]

为了计算 \(frac{{\partial y}}{{\partial {x_i}}}\),可以简单地将 \({{x_1},...{x_{i - 1}},{x_{i + 1}},...{x_n}}\) 看作常数,并计算 \(y\) 关于 \({x_i}\) 的导数,对于偏导数的表示,以下形式等价:

\[\frac{{\partial y}}{{\partial {x_i}}} = \frac{{\partial f}}{{\partial {x_i}}} = {f_{{x_i}}} = {f_i} = {D_i}f = {D_{{x_i}}}f \]

梯度

可以连结一个多元函数对其所有变量的偏导数,以得到该函数的梯度(gradient)向量。设函数 \(f:{R^n} \to R\) 的输入是一个 \(n\) 维向量 \(x = {[{x_1},{x_2},...{x_n}]^T}\) ,并且输出是一个标量。函数 \(f(x)\) 相对于 \(x\) 的梯度是一个包含 \(n\) 个偏导数的向量:

\[{\nabla _x}f(x) = {[\frac{{\partial f(x)}}{{\partial {x_1}}},\frac{{\partial f(x)}}{{\partial {x_2}}},...,\frac{{\partial f(x)}}{{\partial {x_n}}}]^T} \]

其中 \({\nabla _x}f(x)\) 通常在没有歧义时被 \(\nabla f(x)\) 取代。

假设 \(x\)\(n\) 维向量,在微分多元函数时经常使用如下规则:

  • 对于所有 \(A \in {R^{m \times n}}\),都有 \({\nabla _x}Ax = {A^T}\)
  • 对于所有 \(A \in {R^{n \times m}}\),都有 \({\nabla _x}{x^T}A = A\)
  • 对于所有 \(A \in {R^{n \times n}}\),都有 \({\nabla _x}{x^T}Ax = (A + {A^T})x\)
  • \({\nabla _x}{\left\| x \right\|^2} = {\nabla _x}{x^T}x = 2x\)

链式法则

假设函数 \(y = f(u)\)\(u = g(x)\),则根据链式求导法则:

\[\frac{{dy}}{{dx}} = \frac{{dy}}{{du}}\frac{{du}}{{dx}} \]

假设可微分函数 \(y\) 有变量 \(u_1,u_2,...u_m\) 其中,每个可微函数 \(u_i\) 都有变量 \(x_1,x_2,...,x_n\),则根据链式求导法则:

\[\frac{{dy}}{{d{x_i}}} = \frac{{dy}}{{d{u_1}}}\frac{{d{u_1}}}{{d{x_i}}} + \frac{{dy}}{{d{u_2}}}\frac{{d{u_2}}}{{d{x_i}}} + \cdots + \frac{{dy}}{{d{u_m}}}\frac{{d{u_m}}}{{d{x_i}}} \]

posted @ 2022-04-18 13:53  刘-皇叔  阅读(347)  评论(0编辑  收藏  举报