【Pytorch深度学习实战】(1)Pytorch基础知识

🔎大家好,我是Sonhhxg_柒,希望你看完之后,能对你有所帮助,不足请指正!共同学习交流🔎

📝个人主页-Sonhhxg_柒的博客_CSDN博客 📃

🎁欢迎各位→点赞👍 + 收藏⭐️ + 留言📝​

📣系列专栏 - 机器学习【ML】 自然语言处理【NLP】  深度学习【DL】

 🖍foreword

✔说明⇢本人讲解主要包括Python、机器学习(ML)、深度学习(DL)、自然语言处理(NLP)等内容。

如果你对这个系列感兴趣的话,可以关注订阅哟👋


 
 
  1. import torch
  2. import torchvision
  3. import torch.nn as nn
  4. import numpy as np
  5. import torchvision.transforms as transforms

1. 基本 autograd 示例


 
 
  1. # 创建张量。
  2. x = torch.tensor( 1., requires_grad = True)
  3. w = torch.tensor( 2., requires_grad = True)
  4. b = torch.tensor( 3., requires_grad = True)
  5. # 构建计算图。
  6. y = w * x + b # y = 2 * x + 3
  7. # 计算梯度。
  8. y.backward()
  9. # P打印出梯度变化grad。
  10. print(x.grad) # x.grad = 2
  11. print(w.grad) # w.grad = 1
  12. print(b.grad) # b.grad = 1

 
 
  1. # 创建形状为 ( 10, 3) 和 ( 10, 2) 的张量。
  2. x = torch.randn( 10, 3)
  3. y = torch.randn( 10, 2)
  4. # 构建一个全连接层。
  5. linear = nn.Linear( 3, 2)
  6. print ( 'w: ', linear.weight)
  7. print ( 'b: ', linear.bias)
  8. # 构建损失函数和优化器。
  9. criterion = nn.MSELoss()
  10. optimizer = torch.optim.SGD(linear.parameters(), lr = 0.01)
  11. # 前向传播
  12. pred = linear(x)
  13. # 计算损失
  14. loss = criterion(pred, y)
  15. print( 'loss: ', loss.item())
  16. # 后向传播
  17. loss.backward()
  18. # 打印出w和b的grad
  19. print ( 'dL/dw: ', linear.weight.grad)
  20. print ( 'dL/db: ', linear.bias.grad)
  21. # 1-step 梯度下降
  22. optimizer.step()
  23. # 你也可以在低层执行梯度下降。
  24. # linear.weight. data.sub_( 0.01 * linear.weight.grad. data)
  25. # linear.bias. data.sub_( 0.01 * linear.bias.grad. data)
  26. # 打印 1-step 梯度下降后的损失。
  27. pred = linear(x)
  28. loss = criterion(pred, y)
  29. print( 'loss after 1 step optimization: ', loss.item())

2. 从 numpy 加载数据 


 
 
  1. # 创建一个numpy数组。
  2. x = np.array([[ 1, 2], [ 3, 4]])
  3. # 将 numpy 数组转换为 Torch 张量。
  4. y = torch. from_numpy(x)
  5. # 将 Torch 张量转换为 numpy 数组。
  6. z = y.numpy()

3.输入管道


 
 
  1. # 下载并构建 CIFAR- 10 数据集。
  2. train_dataset = torchvision.datasets.CIFAR 10(root = '../../data/',
  3. train = True,
  4. transform =transforms.ToTensor(),
  5. download = True)
  6. # 获取一对数据(从磁盘读取数据)。
  7. image, label = train_dataset[ 0]
  8. print (image. size())
  9. print (label)
  10. # 数据加载器(以非常简单的方式提供队列和线程)。
  11. train_loader = torch.utils. data.DataLoader(dataset =train_dataset,
  12. batch_ size = 64,
  13. shuffle = True)
  14. # 当迭代开始时,队列和线程开始从文件中加载数据。
  15. data_iter = iter(train_loader)
  16. # 小批量图像和标签。
  17. images, labels = data_iter. next()
  18. # 数据加载器的实际使用如下。
  19. for images, labels in train_loader:
  20. # Training code should be written here.
  21. pass

4. 自定义数据集的输入管道 


 
 
  1. # 你应该如下构建你的自定义数据集。
  2. class CustomDataset(torch.utils. data.Dataset):
  3. def __init__( self):
  4. # TODO
  5. # 1. 初始化文件路径或文件名列表。
  6. pass
  7. def __getitem__( self, index):
  8. # TODO
  9. # 1. 从文件中读取一个数据(例如使用numpy.fromfile、PIL.Image. open)。
  10. # 2. 预处理数据(例如torchvision.Transform)。
  11. # 3. 返回一个数据对(例如图像和标签)
  12. pass
  13. def __len__( self):
  14. # 您应该将 0 更改为数据集的总大小。
  15. return 0
  16. # 然后您可以使用预构建的数据加载器。
  17. custom_dataset = CustomDataset()
  18. train_loader = torch.utils. data.DataLoader(dataset =custom_dataset,
  19. batch_ size = 64,
  20. shuffle = True)

5. 预训练模型 


 
 
  1. # 下载并加载预训练的 ResNet- 18
  2. resnet = torchvision.models.resnet 18(pretrained = True)
  3. # 如果只想微调模型的顶层,设置如下。
  4. for param in resnet.parameters():
  5. param.requires_grad = False
  6. # 替换顶层进行微调.
  7. resnet.fc = nn.Linear(resnet.fc. in_features, 100) # 100 is an example.
  8. # 前向传播
  9. images = torch.randn( 64, 3, 224, 224)
  10. outputs = resnet(images)
  11. print (outputs. size()) # ( 64, 100)

6. 保存并加载模型


 
 
  1. # 保存并加载整个模型。
  2. torch.save(resnet, 'model.ckpt')
  3. model = torch.load( 'model.ckpt')
  4. # 仅保存和加载模型参数(推荐)。
  5. torch.save(resnet.state_dict(), 'params.ckpt')
  6. resnet.load_state_dict(torch.load( 'params.ckpt'))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值