矢量化操作
约定
本文中的”向量”均指一维数组/张量,”矩阵”均值二维数组/张量
前言
在ML当中,向量和矩阵非常常见。由于之前使用C语言的惯性,本人经常会从标量的角度考虑向量和矩阵的运算,也就是用for循环来完成向量或矩阵的运算。实际上,for循环的风格比python内置的操作或pytorch的函数要更加耗费时间并且实现起来更复杂。
接下来我将会通过加法和乘法演示矢量化的效果。
加法
首先定义一个矢量加法函数备用:
def tensor_add(a, b):'''only up to 2D tensordo not support broadcasting'''if a.dim() == 1 and b.dim() == 1: # both are vectorslength = a.size(0)c = torch.zeros(length, dtype=a.dtype)for i in range(length):c[i] = a[i] + b[i]return celif a.dim() == 2 and b.dim() == 2: # both are matricesrows, cols = a.size()c = torch.zeros(rows, cols, dtype=a.dtype)for i in range(rows):for j in range(cols):c[i, j]