阅读体验更好
PyTorch
什么是PyTorch(官方文件)
PyTorch 基于以下两个目的python科学计算框架:
-
无缝替换NumPy,并通过使用GPU实现神经网络加速的计算能力。
-
神经网络的实现动微分机制更容易实现。
Tensor(张量)
张量和数组和矩阵一样, 是一种特殊的数据结构。PyTorch中, 网络的输入、输出和参数, 都是用张量来描述的。
张量初始化
import torch import numpy as np #由List直接生成张量, 张量类型由原始数据类型决定。 data = [[1, 2], [3, 4]] x_data = torch.tensor(data) print(f"{
x_data}\n") #通过Numpy生成张量的数组 np_array = np.array(data) x_np = torch.from_numpy(np_array) print(f"{
x_np}\n") ##通过现有的张量生成新的张量 x_ones = torch.ones_like(x_data) # 保留 x_data 的属性() print(f"Ones Tensor: \n {
x_ones} \n") x_rand = torch.rand_like(x_data, dtype=torch.float) # 重写 x_data 的数据类型 #int -> float print(f"Random Tensor: \n {
x_rand} \n") #创建Tensor包括:ones, zeros, eye, arange, linspace, rand, randn, normal, uniform, randperm y_rand = torch.rand(5,3)
print(f"{
y_rand}\n")
x = torch.arange(12)
print(f"{
x}\n")
tensor([[1, 2],
[3, 4]])
tensor([[1, 2],
[3, 4]])
Ones Tensor:
tensor([[1, 1],
[1, 1]])
Random Tensor:
tensor([[0.6913, 0.0076],
[0.0978, 0.3915]])
tensor([[0.3311, 0.6230, 0.4556],
[0.4508, 0.9119, 0.1254],
[0.3226, 0.4033, 0.5625],
[0.1423, 0.4016, 0.3720],
[0.6552, 0.2447, 0.0731]])
tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
张量属性
从张量属性我们可以得到张量的维数、数据类型以及它们所存储的设备(CPU或GPU)。
tensor = torch.rand(3,4)
print(f"Shape of tensor: {
tensor.shape}")
print(f"Datatype of tensor: {
tensor.dtype}")
print(f"Device tensor is stored on: {
tensor.device}")
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu
张量运算
运算例如转置、索引、切片、数学运算、线性代数、随机采样等,下面是一些常见的张量运算,其他有需要的话再查阅官方文档即可
运算符
x = torch.tensor([1.0, 2, 4, 8])
y = torch.tensor([2, 2, 2, 2])
x + y, x - y, x * y, x / y, x ** y,torch.exp(x) # **运算符是求幂运算
(tensor([ 3., 4., 6., 10.]),
tensor([-1., 0., 2., 6.]),
tensor([ 2., 4., 8., 16.]),
tensor([0.5000, 1.0000, 2.0000, 4.0000]),
tensor([ 1., 4., 16., 64.])
tensor([2.7183e+00, 7.3891e+00, 5.4598e+01, 2.9810e+03]))
拼接
通过torch.cat方法将一组张量按照指定的维度进行拼接
X = torch.arange(12, dtype=torch.float32).reshape((3,4))
Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
torch.cat((X, Y), dim=0), torch.cat((X, Y), dim=1)
(tensor([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[ 2., 1., 4., 3.],
[ 1., 2., 3., 4.],
[ 4., 3., 2., 1.]]),
tensor([[ 0., 1., 2., 3., 2., 1., 4., 3.],
[ 4., 5., 6., 7., 1., 2., 3., 4.],
[ 8., 9., 10., 11., 4., 3., 2., 1.]]))
索引和切片
和Python数组一样,张量的元素支持索引,切片
print(X)
print(X[-1])
print(X[1:3])
print(X[0][0:2])
tensor([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]])
tensor([ 8., 9., 10., 11.])
tensor([[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]])
tensor([0., 1.])
数学基础
线性代数
基本概念:
-
标量 (scalar) :标量由只有一个元素的张量表示
-
向量 (vector) :将标量从零阶推广到一阶 x ∈ R n \mathbf{x}\in\mathbb{R}^n x∈Rn
-
矩阵 (matrix) :矩阵将向量从一阶推广到二阶, A ∈ R m × n \mathbf{A} \in \mathbb{R}^{m \times n} A∈Rm×n
-
矩阵的转置(transpose),对称矩阵(symmetric matrix),正交矩阵(Orthogonal Matrix),矩阵乘法
-
范数 (norm) : L 1 L_1 L1范数: ∥ x ∥ 1 = ∑ i = 1 n ∣ x i ∣ . \|\mathbf{x}\|_1 = \sum_{i=1}^n \left|x_i \right|. ∥x∥1=i=1∑n∣xi∣.
L 2 L_2 L2范数: ∥ x ∥ 2 = ∑ i = 1 n x i 2 , \|\mathbf{x}\|_2 = \sqrt{\sum_{i=1}^n x_i^2}, ∥x∥2=i=1∑nxi2 ,
F − F- F−范数(矩阵): ∥ X ∥ F = ∑ i = 1 m ∑ j = 1 n x i j 2 . \|\mathbf{X}\|_F = \sqrt{\sum_{i=1}^m \sum_{j=1}^n x_{ij}^2}. ∥X∥F=i=1∑mj=1∑nxij2 .
-
…
微积分
矩阵求导:
矩阵求导的本质与分子布局、分母布局的本质
矩阵求导公式的数学推导
矩阵求导公式的数学推导
概率
基本概念:
- 样本空间(sample space)事件(event)互斥(mutually exclusive)
- 随机变量(random variable)离散(discrete)连续(continuous)
- 条件概率(conditional probability)Bayes定理(Bayes’ theorem)
- 联合分布(joint distribution)边缘分布(marginal distribution)。
- 期望(expectation)标准差(standard deviation)
- 马尔可夫链
- …
线性神经网络
虽然线性神经网络的功能很有限,但它是一切的基础。
线性回归及其实现
基本元素
在机器学习的术语中,该数据集称为训练数据集(training data set) 或训练集(training set)。 每行数据样本(sample), 也可以称为数据点(data point)或数据样本(data instance)。 我们把试图预测的目标称为标签(label)或目标(target)。 预测所依据的自变量称为特征(feature)或协变量(covariate)。
通常,我们使用 n n n来表示数据集中的样本数。对索引为 i i i的样本,其输入表示为 x ( i ) = [ x 1 ( i ) , x 2 ( i ) ] ⊤ \mathbf{x}^{(i)} = [x_1^{(i)}, x_2^{(i)}]^\top x(i)=[x1(i),x2(i)]⊤,其对应的标签是 y ( i ) y^{(i)} y(i)。
线性模型
当我们的输入包含 d d d个特征时,我们将预测结果 y ^ \hat{y} y^(通常使用“尖角”符号表示 y y y的估计值)表示为:
y ^ = w 1 x 1 + . . . + w d x d + b . \hat{y} = w_1 x_1 + ... + w_d x_d + b. y^=w1x1+...+wdxd+b. 将所有特征放到向量 x ∈ R d \mathbf{x} \in \mathbb{R}^d x∈Rd中,并将所有权重放到向量 w ∈ R d \mathbf{w} \in \mathbb{R}^d w∈Rd中,我们可以用点积形式来简洁地表达模型:
y ^ = w ⊤ x + b . \hat{y} = \mathbf{w}^\top \mathbf{x} + b. y^=w⊤x+b.
损失函数(loss function)
平方损失函数,一般这样定义: l ( i ) ( w , b ) = 1 2 ( y ^ ( i ) − y ( i ) ) 2 . l^{(i)}(\mathbf{w}, b) = \frac{1}{2} \left(\hat{y}^{(i)} - y^{(i)}\right)^2. l(i)(w,b)=21(y^(i)−y(i))2.]
其实平方损失函数就是对参数的极大似然估计通俗讲解平方损失函数平方形式的数学解释?
小批量随机梯度下降(minibatch stochastic gradient descent)
梯度下降(gradient descent):通过不断地在损失函数递减的方向上更新参数来降低误差。但实际中的执行可能会非常慢:因为在每一次更新参数之前,我们必须遍历整个数据集。 因此,我们通常会在每次需要计算更新的时候随机抽取一小批样本, 这种变体叫做小批量随机梯度下降(minibatch stochastic gradient descent)。
在每次迭代中,我们首先随机抽样一个小批量 B \mathcal{B} B, 然后,我们计算小批量的平均损失关于模型参数的导数(梯度)。 最后,我们将梯度乘以一个预先确定的正数𝜂(学习率),并从当前参数的值中减掉。 ( w , b ) ← ( w , b ) − η ∣ B ∣ ∑ i ∈ B ∂ ( w , b ) l ( i ) ( w , b ) (\mathbf{w},b) \leftarrow (\mathbf{w},b) - \frac{\eta}{|\mathcal{B}|} \sum_{i \in \mathcal{B}} \partial_{(\mathbf{w},b)} l^{(i)}(\mathbf{w},b) (w,b)←(w,b)−∣B∣ηi∈B∑∂(w,b)l(i)(w,b)
代码实现 参考网站
参数 w = [ 2 , − 3.4 ] ⊤ \mathbf{w} = [2, -3.4]^\top 标签: 5w33kr电阻5w33r精密电阻