线性回归

我们对计算进行矢量化,从而利用线性代数库,而不是在Python中编写开销高昂的for循环

In [1]:
%matplotlib inline
import math
import time
import numpy as np
import torch
from d2l import torch as d2l

对向量相加的两种方法

In [2]:
n = 10000
a = torch.ones(n)
b = torch.ones(n)

我们定义一个计时器

In [3]:
class Timer:  
    """记录多次运行时间。"""
    def __init__(self):
        self.times = []
        self.start()

    def start(self):
        """启动计时器。"""
        self.tik = time.time()

    def stop(self):
        """停止计时器并将时间记录在列表中。"""
        self.times.append(time.time() - self.tik)
        return self.times[-1]

    def avg(self):
        """返回平均时间。"""
        return sum(self.times) / len(self.times)

    def sum(self):
        """返回时间总和。"""
        return sum(self.times)

    def cumsum(self):
        """返回累计时间。"""
        return np.array(self.times).cumsum().tolist()

我们使用for循环,每次执行一位的加法

In [4]:
c = torch.zeros(n)
timer = Timer()
for i in range(n):
    c[i] = a[i] + b[i]
f'{timer.stop():.5f} sec'
Out[4]:
'0.11435 sec'

或者,我们使用重载的 + 运算符来计算按元素的和

In [5]:
timer.start()
d = a + b
f'{timer.stop():.5f} sec'
Out[5]:
'0.00052 sec'

我们定义一个Python函数来计算正态分布

In [6]:
def normal(x, mu, sigma):
    p = 1 / math.sqrt(2 * math.pi * sigma**2)
    return p * np.exp(-0.5 / sigma**2 * (x - mu)**2)

可视化正态分布

In [7]:
x = np.arange(-7, 7, 0.01)

params = [(0, 1), (0, 2), (3, 1)]
d2l.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])
2021-05-15T04:07:08.016900 image/svg+xml Matplotlib v3.3.4, https://matplotlib.org/