Pytorch学习系列(1):Pytorch基础

Pytorch学习系列(1):Pytorch基础

由于科研需要这里开一个新坑,学习如何使用Pytorch进行炼丹,目前想法是快速把基本功能都过一遍,以后具体项目用到的时候能够快速查找。

我是直接在Pycharm里面直接安装的Pytorch,版本:

import torch
print(torch.__version__) 
1.9.1+cpu

autograd(自动求导 / 求梯度) 基础案例 1

# 创建张量(tensors)
x = torch.tensor(1., requires_grad=True)
w = torch.tensor(2., requires_grad=True)
b = torch.tensor(3., requires_grad=True)

# 构建计算图(computational graph):前向计算
y = w * x + b    # y = 2 * x + 3

# 反向传播,计算梯度(gradients)
y.backward()

# 输出梯度
print(x.grad)    # x.grad = 2 
print(w.grad)    # w.grad = 1 
print(b.grad)    # b.grad = 1 
tensor(2.)
tensor(1.)
tensor(1.)

autograd(自动求导 / 求梯度) 基础案例 2

# 创建大小为 (10, 3) 和 (10, 2)的张量.
x = torch.randn(10, 3)
y = torch.randn(10, 2)

# 构建全连接层(fully connected layer)
linear = nn.Linear(3, 2)
print ('w: ', linear.weight)
print ('b: ', linear.bias)

# 构建损失函数和优化器(loss function and optimizer)
# 损失函数使用均方差
# 优化器使用随机梯度下降,lr是learning rate
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(linear.parameters(), lr=0.01)

# 前向传播
pred = linear(x)

# 计算损失
loss = criterion(pred, y)
print('loss: ', loss.item())

# 反向传播
loss.backward()

# 输出梯度
print ('dL/dw: ', linear.weight.grad) 
print ('dL/db: ', linear.bias.grad)

# 执行一步-梯度下降(1-step gradient descent)
optimizer.step()

# 更底层的实现方式是这样子的
# linear.weight.data.sub_(0.01 * linear.weight.grad.data)
# linear.bias.data.sub_(0.01 * linear.bias.grad.data)

# 进行一次梯度下降之后,输出新的预测损失
# loss的确变少了
pred = linear(x)
loss = criterion(pred, y)
print('loss after 1 step optimization: ', loss.item())
w:  Parameter containing:
tensor([[-0.2353, -0.1131,  0.0990],
        [ 0.0522, -0.2579, -0.3923]], requires_grad=True)
b:  Parameter containing:
tensor([-0.2321,  0.0646], requires_grad=True)
loss:  1.4495947360992432
dL/dw:  tensor([[-0.0395,  0.3244, -0.3342],
        [ 0.1344, -0.2000, -0.6633]])
dL/db:  tensor([-0.3577,  0.8783])
loss after 1 step optimization:  1.4335315227508545

从 Numpy 装载数据

# 创建Numpy数组
x = np.array([[1, 2], [3, 4]])
print(x)

# 将numpy数组转换为torch的张量
y = torch.from_numpy(x)
print(y)

# 将torch的张量转换为numpy数组
z = y.numpy()
print(z)
[[1 2]
 [3 4]]
tensor([[1, 2],
        [3, 4]], dtype=torch.int32)
[[1 2]
 [3 4]]

输入工作流(Input pipeline)

# 下载和构造CIFAR-10 数据集
# Cifar-10数据集介绍:https://www.cs.toronto.edu/~kriz/cifar.html
train_dataset = torchvision.datasets.CIFAR10(root='../../../data/',
                                             train=True, 
                                             transform=transforms.ToTensor(),
                                             download=True)

# 获取一组数据对(从磁盘中读取)
image, label = train_dataset[0]
print (image.size())
print (label)

# 数据加载器(提供了队列和线程的简单实现)
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
                                           batch_size=64, 
                                           shuffle=True)

# 迭代的使用
# 当迭代开始时,队列和线程开始从文件中加载数据
data_iter = iter(train_loader)

# 获取一组mini-batch
images, labels = data_iter.next()


# 正常的使用方式如下:
for images, labels in train_loader:
    # 在此处添加训练用的代码
    pass
Files already downloaded and verified
torch.Size([3, 32, 32])
6

自定义数据集的 Input pipeline

# 构建自定义数据集的方式如下:
class CustomDataset(torch.utils.data.Dataset):
    def __init__(self):
        # TODO
        # 1. 初始化文件路径或者文件名
        pass
    def __getitem__(self, index):
        # TODO
        # 1. 从文件中读取一份数据(比如使用nump.fromfile,PIL.Image.open)
        # 2. 预处理数据(比如使用 torchvision.Transform)
        # 3. 返回数据对(比如 image和label)
        pass
    def __len__(self):
        # 将0替换成数据集的总长度
        return 0 

# 然后就可以使用预置的数据加载器(data loader)了
custom_dataset = CustomDataset()
train_loader = torch.utils.data.DataLoader(dataset=custom_dataset,
                                           batch_size=64, 
                                           shuffle=True)

预训练模型

# 下载并加载预训练好的模型 ResNet-18
resnet = torchvision.models.resnet18(pretrained=True)


# 如果想要在模型仅对Top Layer进行微调的话,可以设置如下:
# requieres_grad设置为False的话,就不会进行梯度更新,就能保持原有的参数
for param in resnet.parameters():
    param.requires_grad = False    

# 替换TopLayer,只对这一层做微调
resnet.fc = nn.Linear(resnet.fc.in_features, 100)  # 100 is an example.

# 前向传播
images = torch.randn(64, 3, 224, 224)
outputs = resnet(images)
print (outputs.size())     # (64, 100)
torch.Size([64, 100])

保存和加载模型

# 保存和加载整个模型
torch.save(resnet, 'model.ckpt')
model = torch.load('model.ckpt')

# 仅保存和加载模型的参数(推荐这个方式)
torch.save(resnet.state_dict(), 'params.ckpt')
resnet.load_state_dict(torch.load('params.ckpt'))
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇