沐神动手深度学习 05线性回归

# 我们对计算进行矢量化,从而利用线性代数库,而不是在Python中编写开销高昂的for循环
%matplotlib inline
import math
import time
import numpy as np
import torch
from d2l import torch as d2l
# 对向量相加的两种方法
n = 10000
a = torch.ones(n)
b = torch.ones(n)
# 我们定义一个计时器
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循环,每次执行一位的加法
c = torch.zeros(n)
timer = Timer()
# 开始计算时间
for i in range(n):
    c[i] = a[i] + b[i]
f'{timer.stop():.5f} sec'
# 计算花费的总时间

‘0.06705 sec’

# 或者,我们使用重载的 + 运算符来计算按元素的和
timer.start()
d = a + b
f'{timer.stop():.5f} sec'

‘0.00082 sec’

# 我们定义一个Python函数来计算正态分布
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)
    # 可视化正态分布
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])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值