【CS191】【lab1】part1


PyTorch 入门与音乐生成实验笔记

实验目标

本实验旨在通过 PyTorch 框架,学习深度学习的基本概念,包括张量操作、神经网络定义、自动微分以及简单的优化过程。实验分为多个部分,逐步深入 PyTorch 的核心功能。

实验环境

  • PyTorch:一个流行的深度学习库,以其灵活性和易用性而闻名。
  • 其他依赖torch.nnnumpymatplotlib 等。

实验内容

1. PyTorch 基础:张量操作

张量是 PyTorch 中的基本数据结构,可以看作是多维数组。张量的形状(shape)定义了其维度和每个维度的大小。

创建张量

  • 标量

    1
    2
    integer = torch.tensor(1234)
    decimal = torch.tensor(3.14159265359)

    输出:

    1
    2
    `integer` is a 0-d Tensor: 1234  
    `decimal` is a 0-d Tensor: 3.1415927410125732
  • 向量

    1
    2
    fibonacci = torch.tensor([1, 1, 2, 3, 5, 8])
    count_to_100 = torch.tensor(range(100))

    输出:

    1
    2
    `fibonacci` is a 1-d Tensor with shape: torch.Size([6])  
    `count_to_100` is a 1-d Tensor with shape: torch.Size([100])
  • 矩阵和高阶张量

    1
    2
    matrix = torch.tensor([[1, 2], [2, 3]])
    images = torch.zeros(10, 3, 256, 256) # 10 张 256x256 的 RGB 图像

    输出:

    1
    images is a 4-d Tensor with shape: torch.Size([10, 3, 256, 256])

张量切片

通过切片操作可以访问高阶张量的子张量:

1
2
3
row_vector = matrix[1]  # 第二行
column_vector = matrix[:, 1] # 第二列
scalar = matrix[0, 1] # 第一行第二列的元素

输出:

1
2
3
`row_vector`: tensor([2, 3])  
`column_vector`: tensor([2, 3])
`scalar`: 2

2. 张量计算

在 PyTorch 中,计算可以通过操作张量来实现。这些操作可以被看作是计算图的一部分。

简单计算

1
2
3
4
a = torch.tensor(15)
b = torch.tensor(61)
c1 = torch.add(a, b) # 使用 PyTorch 函数
c2 = a + b # 使用重载的 "+" 操作符

输出:

1
2
c1: 76  
c2: 76

复杂计算

定义一个简单的计算函数:

1
2
3
4
5
def func(a, b):
c = a + b
d = b - 1
e = c * d
return e

调用函数:

1
2
a, b = 1.5, 2.5
e_out = func(a, b)

输出:

1
e_out: 6.0

3. 神经网络定义

PyTorch 使用 torch.nn.Module 作为所有神经网络模块的基类,提供了构建和训练神经网络的框架。

自定义单层网络

定义一个简单的感知机网络:

1
2
3
4
5
6
7
8
9
10
class OurDenseLayer(torch.nn.Module):
def __init__(self, num_inputs, num_outputs):
super(OurDenseLayer, self).__init__()
self.W = torch.nn.Parameter(torch.randn(num_inputs, num_outputs))
self.bias = torch.nn.Parameter(torch.randn(num_outputs))

def forward(self, x):
z = torch.matmul(x, self.W) + self.bias
y = torch.sigmoid(z)
return y

测试输出:

1
2
3
layer = OurDenseLayer(2, 3)
x_input = torch.tensor([[1, 2.]])
y = layer(x_input)

输出:

1
2
3
input shape: torch.Size([1, 2])  
output shape: torch.Size([1, 3])
output result: tensor([[0.9352, 0.2640, 0.9645]], grad_fn=<SigmoidBackward0>)

使用 Sequential API

使用 PyTorch 的 nn.Sequential 定义一个简单的神经网络:

1
2
3
4
model = nn.Sequential(
nn.Linear(in_features=2, out_features=3), # 线性层
nn.ReLU() # 非线性激活函数
)

测试输出:

1
2
x_input = torch.tensor([[1, 2.]])
model_output = model(x_input)

输出:

1
2
3
input shape: torch.Size([1, 2])  
output shape: torch.Size([1, 3])
output result: tensor([[0.9352, 0.2640, 0.9645]], grad_fn=<SigmoidBackward0>)

4. 自动微分

PyTorch 使用 torch.autograd 实现自动微分,这是训练深度学习模型的关键。

计算梯度

1
2
3
4
x = torch.tensor(3.0, requires_grad=True)
y = x ** 2
y.backward()
dy_dx = x.grad

输出:

1
dy_dx of y=x^2 at x=3.0 is: tensor(6.)

使用梯度下降优化

通过梯度下降优化一个简单的损失函数:

1
2
3
4
5
6
7
8
9
x = torch.randn(1)  # 初始化随机值
learning_rate = 1e-2
x_f = 4 # 目标值

for i in range(500):
x = torch.tensor([x], requires_grad=True)
loss = (x - x_f) ** 2 # 损失函数:均方误差
loss.backward()
x = x - learning_rate * x.grad

文章作者: MIKA
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 MIKA !
  目录