注:本代码在jupyter notebook上运行
封面图片来源
1 、矢量化加速
在训练模型时, 为了实现同时处理整个小批量的样本,需要对计算进行矢量化, 从而利用线性代数库,而不是在Python中编写开销高昂的for循环。
%matplotlib inline
# %matplotlib inline 是一个IPython魔术命令(magic command),主要用于Jupyter Notebook或IPython环境中,用于控制matplotlib绘图的显示方式。当你在Jupyter Notebook中运行这个命令时,它会使得matplotlib生成的图表直接嵌入到Notebook的输出中,而不是在新的窗口中打开。
import math
import time
import numpy as np
import torch
# from d2l import torch as d2l
# 两个全为1的10000维向量
n = 10000
a = torch.ones([n])
b = torch.ones([n])
定义计时器
class Timer: #@save
"""记录多次运行时间"""
def __init__(self):
self.times = []
self.start()
def start(self):
"""启动计时器"""
self.tik = time.time()
def stop(self):
"""停止计时器并将时间记录在列表中"""
self.times