pytorch的安装

在已经安装的python环境的前提下,只需要在命令行输入

1
pip install torch torchvision torchaudio

即可。

预备知识

基本函数

  1. torch.empty(int size,int size)

    创建一个指定大小的张量,张量中的值是未初始化的,也就是任意的,参数代表的是张量的维度

    1
    x = torch.empty(5, 3)
  2. torch.zeros(int,int,dtype)

    创建指定大小的张量,所有元素初始化为0,第三个参数指定元素的类型

    1
    x = torch.zeros(5, 3, dtype=torch.long)
  3. torch.rand(int,int)

    创建指定大小的随机张量,元素的值是随机从0到1的区间取的

    1
    x = torch.rand(5, 3)
  4. torch.tensor()

    手动创建一个张量,自己给定数字进行创建

    1
    x = torch.tensor([5.5, 3])
  5. torch.add(x,y)

    对两个张量进行逐元素相加的操作,x,y这两个张量的形状必须相同

    1
    torch.add(x, y)

矩阵乘法

  1. torch.matmul()

    最通用的矩阵乘法,能处理高位数据

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    import torch

    # 创建两个2x3和3x2的矩阵
    a = torch.tensor([[1, 2, 3],
    [4, 5, 6]])
    b = torch.tensor([[7, 8],
    [9, 10],
    [11, 12]])

    # 矩阵乘法
    c = torch.matmul(a, b)
    print(c)
  2. torch.mm()

    专门用于二维矩阵的乘法。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    import torch

    # 创建两个2x3和3x2的矩阵
    a = torch.tensor([[1, 2, 3],
    [4, 5, 6]])
    b = torch.tensor([[7, 8],
    [9, 10],
    [11, 12]])

    # 矩阵乘法
    c = torch.mm(a, b)
    print(c)
  3. @运算符

    功能和torch.matmul()一样。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    import torch

    # 创建两个2x3和3x2的矩阵
    a = torch.tensor([[1, 2, 3],
    [4, 5, 6]])
    b = torch.tensor([[7, 8],
    [9, 10],
    [11, 12]])

    # 矩阵乘法
    c = a @ b
    print(c)

数学定义和运算

矩阵的点乘(哈达玛积)

对应位置的元素进行相乘,不是矩阵乘法

梯度

  • .backward()方法
  • .grad()方法

自动求导(Autigrad)

在张量创建时设置,requires_grad = True,Pytorch就会开始对追踪对该张量的所有操作,完成计算后调用 .backward就会计算所有梯度并复制到.grad属性里面。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 创建一个张量并设置requires_grad=True用来追踪其计算历史
x = torch.ones(2, 2, requires_grad=True)

# 对张量进行操作
y = x + 2
z = y * y * 3
out = z.mean()

# 计算梯度
out.backward()

# 打印梯度 d(out)/dx
print(x.grad)
#答案是2*2的元素均4.5的矩阵

建立神经网络前应该知道的

.liear()方法

.liear(in_features,out_features)创建一个线性的映射关系,用线性函数来计算输出,这个线性函数可以表示为

$x$是输入的向量,大小由in_features决定,$A$是权重矩阵,由电脑根据输入输出的特征值自动生成,一般使用均匀分布或正态分布,$b$是偏置向量(Bias),通常初始化为0,这是因为偏置的初值通常不会对网络初期的学习造成太大影响,而且从零开始可以保持初始化的简单性。(这里的转置计算是出于编程的便利考虑,无深意)

$x$可以是一个多维的向量,也就是矩阵,我们把这种情况叫做批处理

1
2
3
4
5
6
7
8
9
10
import torch

# 假设每个样本有2个特征
features = torch.tensor([[1.0, 2.0], [1.5, 2.5], [2.0, 3.0], [2.5, 3.5]])
# 这里 features 的大小是 [4, 2]
# 4 是批处理大小,2 是特征数量

layer = torch.nn.Linear(2, 3)
output = layer(features)
print(output)

最后得到的是一个$[4\times 3]$的矩阵

torch.nn

torch.nn提供很多预定的层,比如全连接层(Linear),卷积层(Conv2d),池化层(MaxPool2d)等

torch.nn.functional

torch.nn.functional包含了torch.nn里面层的函数实现,每个操作可以通过它来作为为一个独立的函数使用,而不需要事先创建对象。

激活函数

引入非线性性质,使得神经网络可以学习和模拟复杂的函数,如分类边界和连续的函数映射。

常见的激活函数有

  • ReLU:对输入执行非线性变换$f(x)=max(0,x)$
  • Sigmoid:将输入压缩到0到1之间,常用于二分类问题中
  • Tanh:将输入压缩到-1和1之间,形状和Sigmoid类似但是输出范围更广
  • Softmax:常用于多酚类问题的输出层,会将输入转换为概率分布

super函数继承父类

super是python的内置函数,用于调用父类(超类)的方法。常用于构造函数中,确保父类被正确初始化,也可以用来调用其他继承自父类的方法。super内部的参数可以不写(python3)。

super函数的用法

1
2
3
4
5
6
7
8
9
10
class Parent:
def __init__(self):
print("Parent __init__")

class Child(Parent):
def __init__(self):
super().__init__()
print("Child __init__")

child = Child()

构建简单的神经网络

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import torch
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):

def __init__(self):
super(Net, self).__init__()
# 定义网络层
self.fc1 = nn.Linear(2, 3) # 2输入到3输出
self.fc2 = nn.Linear(3, 2)

def forward(self, x):
# 定义前向传播
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x

# 实例化网络
net = Net()
print(net)