PyTorch 基础篇(1):Pytorch 基础

Pytorch 学习开始

入门的材料来自两个地方:

第一个是官网教程:WELCOME TO PYTORCH TUTORIALS,特别是官网的六十分钟入门教程 DEEP LEARNING WITH PYTORCH: A 60 MINUTE BLITZ。

第二个是韩国大神 Yunjey Choi 的 Repo:pytorch-tutorial,代码写得干净整洁。

目的:我是直接把 Yunjey 的教程的 python 代码挪到 Jupyter Notebook 上来,一方面可以看到运行结果,另一方面可以添加注释和相关资料链接。方便后面查阅。

顺便一题,我的 Pytorch 的版本是 0.4.1

复制代码
  
  
  
   
* import torch

   
* print(torch.version)

  
复制代码
  
  
  
   
* 0.4.1

  
复制代码
  
  
  
   
* # 包

   
* import torch 

   
* import torchvision

   
* import torch.nn as nn

   
* import numpy as np

   
* import torchvision.transforms as transforms

  

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.5180,  0.2238, -0.5470],

   
*         [ 0.1531,  0.2152, -0.4022]], requires_grad=True)

   
* b:  Parameter containing:

   
* tensor([-0.2110, -0.2629], requires_grad=True)

   
* loss:  0.8057981729507446

   
* dL/dw:  tensor([[-0.0315,  0.1169, -0.8623],

   
*         [ 0.4858,  0.5005, -0.0223]])

   
* dL/db:  tensor([0.1065, 0.0955])

   
* loss after 1 step optimization:  0.7932316660881042

  

从 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]])

   
* [[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'))

  
相关推荐
开MINI的工科男33 分钟前
深蓝学院-- 量产自动驾驶中的规划控制算法 小鹏
人工智能·机器学习·自动驾驶
waterHBO40 分钟前
python 爬虫 selenium 笔记
爬虫·python·selenium
编程零零七2 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
AI大模型知识分享2 小时前
Prompt最佳实践|如何用参考文本让ChatGPT答案更精准?
人工智能·深度学习·机器学习·chatgpt·prompt·gpt-3
张人玉4 小时前
人工智能——猴子摘香蕉问题
人工智能
草莓屁屁我不吃4 小时前
Siri因ChatGPT-4o升级:我们的个人信息还安全吗?
人工智能·安全·chatgpt·chatgpt-4o
AIAdvocate4 小时前
Pandas_数据结构详解
数据结构·python·pandas
小言从不摸鱼4 小时前
【AI大模型】ChatGPT模型原理介绍(下)
人工智能·python·深度学习·机器学习·自然语言处理·chatgpt
AI科研视界4 小时前
ChatGPT+2:修订初始AI安全性和超级智能假设
人工智能·chatgpt
霍格沃兹测试开发学社测试人社区4 小时前
人工智能 | 基于ChatGPT开发人工智能服务平台
软件测试·人工智能·测试开发·chatgpt