统一 MXNet,PyTorch,TensorFlow 接口


为了提供一个统一的接口,我在 GitHub 上维护了一个通用 API:atom。可以使用 pip 安装。本仓库借鉴了 d2l简单粗暴 TensorFlow 2

首先导入一些库:

python
python
from xint import utils
from xint import mxnet as xint

np = xint.np
python
python
from xint import utils
from xint import tensorflow as xint

np = xint.np
python
python
from xint import utils
from xint import torch as xint

np = xint.np

简单的使用 atom

由于 np 已经绑定了各自的深度学习环境,且三种框架及其相似,所以,下文如果框架之间没有分歧,统一使用没有指示环境的模式,比如:

python
python
n = 10000
a = np.ones(n)
b = np.zeros(n)

你可以分别查看各自环境的数据:

python
python
a
array([1., 1., 1., ..., 1., 1., 1.])
python
python
a
<ndarray<<tf.Tensor: shape=(10000,), dtype=float64, numpy=array([1., 1., 1., ..., 1., 1., 1.])>>
python
python
a
tensor([1., 1., 1., ..., 1., 1., 1.])

可以看到不同环境表示的不同的 np,可以无缝的使用它。

atom 定义了一个计时器 Timer,下面测试矢量化的好处。

  1. 使用 for 循环:
python
python
c = np.zeros(n)
timer = utils.Timer()
for i in range(n):
    c[i] = a[i] + b[i]
f'{timer.stop():.5f} sec'
'2.83601 sec'
python
python
import tensorflow as tf

c = tf.Variable(tf.zeros(n))
timer = utils.Timer()
for i in range(n):
    c[i].assign(a[i] + b[i])
f'{timer.stop():.5f} sec'
'3.42657 sec'
python
python
c = np.zeros(n)
timer = utils.Timer()
for i in range(n):
    c[i] = a[i] + b[i]
f'{timer.stop():.5f} sec'
'0.13695 sec'
  1. 使用重载的 + 运算符来计算按张量的和。
python
python
timer.start()
d = a + b
f'{timer.stop():.9f} sec'

输出的时间有点差异,但是都很快:

'0.0009992 sec'
'0.000999451 sec'
'0.000944614 sec'

可以看出矢量化对运算速度的提升是数量级的。

正态分布与平方损失

正态分布(normal distribution),也被称为 高斯分布(Gaussian distribution),最早由德国数学家高斯(Gauss)应用于天文学研究。简单的说,若随机变量 xx 具有均值 μ\mu 和方差 σ2\sigma^2(标准差 σ\sigma),其正态分布概率密度函数如下:

p(x)=12πσ2exp(12σ2(xμ)2). p(x) = \frac{1}{\sqrt{2 \pi \sigma^2}} \exp\left(-\frac{1}{2 \sigma^2} (x - \mu)^2\right).

使用 np 可以实现:

python
python
def normal(x, mu, sigma):
    p = 1 / np.sqrt(2 * np.pi * sigma**2)
    return p * np.exp(-0.5 / sigma**2 * (x - mu)**2)

可视化正态分布:

python
python
x = np.arange(-7, 7, 0.01)

# 均值和标准差对
params = [(0, 1), (0, 2), (3, 1)]
utils.plot(x, [normal(x, mu, sigma) for mu, sigma in params], xlabel='x',
           ylabel='p(x)', figsize=(4.5, 2.5),
           legend=[f'mean {mu}, std {sigma}' for mu, sigma in params])

改变均值会产生沿 xx 轴的偏移,增加方差将会分散分布、降低其峰值。

利用均方误差损失函数(简称均方损失)可以用于线性回归的一个原因是:假设观测 x\mathbf{x} 中包含噪声,其中噪声服从正态分布。噪声正态分布如下式:

y=wx+b+ϵ where ϵN(0,σ2).(1.1)\tag{1.1} y = \mathbf{w}^\top \mathbf{x} + b + \epsilon \text{ where } \epsilon \sim \mathcal{N}(0, \sigma^2).

因此,我们现在可以写出通过给定的观测 x\mathbf{x} 到特定 yy 的似然(likelihood):

P(yx)=12πσ2exp(12σ2(ywxb)2).(1.2)\tag{1.2} P(y \mid \mathbf{x}) = \frac{1}{\sqrt{2 \pi \sigma^2}} \exp\left(-\frac{1}{2 \sigma^2} (y - \mathbf{w}^\top \mathbf{x} - b)^2\right).

根据最大似然估计法,参数 w\mathbf{w}bb 的最优值是使整个数据集的似然最大的值:

P(yX)=i=1np(y(i)x(i)).(1.3)\tag{1.3} P(\mathbf y \mid \mathbf X) = \prod_{i=1}^{n} p(y^{(i)}|\mathbf{x}^{(i)}).

根据最大似然估计法选择的估计量称为最大似然估计量 。为了更好的计算,可以最小化负对数似然 logP(yX)-\log P(\mathbf y \mid \mathbf X)。由此可以得到的数学公式是:

logP(yX)=i=1n12log(2πσ2)+12σ2(y(i)wx(i)b)2.(1.4)\tag{1.4} -\log P(\mathbf y \mid \mathbf X) = \sum_{i=1}^n \frac{1}{2} \log(2 \pi \sigma^2) + \frac{1}{2 \sigma^2} \left(y^{(i)} - \mathbf{w}^\top \mathbf{x}^{(i)} - b\right)^2.

现在我们只需要假设 σ\sigma 是某个固定常数就可以忽略第一项,因为第一项不依赖于 w\mathbf{w}bb。现在第二项除了常数 1σ2\frac{1}{\sigma^2} 外,其余部分和前面介绍的平方误差损失是一样的。因此,在高斯噪声的假设下,最小化均方误差等价于对线性模型的最大似然估计


文章作者: xinetzone
版权声明: 本博客所有文章除特别声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 xinetzone !
评论

Related Issues not found

Please contact @xinetzone to initialize the comment