导入库
'''矢量化加速'''
%matplotlib inline
import math
import time
import numpy as np
import torch
from d2l import torch as d2l
# matplotlib错误 加下面两句代码
# import matplotlib
# matplotlib.use('TkAgg') #出现问题加上这一句
生成数据
n = 10000
a = torch.ones([n])
b = torch.ones([n])
# print(a,type(a))
# print(b,type(b))
定义时间类
# 定义时间类
class Timer:
# 记录多次运行时间
def __init__(self):
self.times = []
self.start()
# 启动计时器
def start(self):
self.tik = time.time()
# 停止计时器,并将时间记录到times列表中
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循环和 + 运算符测试速度
'''使用for循环执行'''
c = torch.zeros(n)
timer = Timer()
for i in range(n):
c[i] = a[i] + b[i]
print(f'{timer.stop():.5f} sec')
# 使用重载的 + 运算符来计算按元素的和
timer.start()
d = a+b
print(f'{timer.stop():.5f} sec')
0.17055 sec
0.00100 sec
正态分布情况
'''正态分布'''
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)
# 再次使用numpy进行可视化
x = np.arange(-7,7,0.01)
print(x)
# 均值和标准差对
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])
[-7. -6.99 -6.98 ... 6.97 6.98 6.99]
