pytorch新手自学教程(一)

Pytorch详细新手自学教程(一)

前言

本教程参考书籍《深度学习入门之pytorch》
-----关于pytorch的优点这里不再说明,毕竟现在的主流仍然是TensorFlow。
1、环境配置可到pytorch官网搜索下载包的pip或conda指令,然后用cmd安装就行。前提是电脑里已经安装了pip或者conda并配置了相应的环境变量。
2、学习之前最好先了解python的numpy和matplotlib包,不过也可以边学边查一下相关用法
3、代码中使用包定义如下:

import torch
import numpy as np
import matplotlib.pyplot as plt

from torch.autograd import Variable

Tensor(张量)

tensor的数据类型:32 位浮点型 torch.Float Tensor、 64 位浮点型 torch.DoubleTensor、 16 位整型 torch.Shor tTensor、 32 位 整型 torch.lntTensor 和 64 位整型 torch.LongTensor, torch.Tensor 默认的是 torch.FloatTensor 数据类型。
·定义一个tensor:

1 a = torch. Tensor ( [ [2 , 3], [ 4 , 8], [7, 9 ] ] )#定义一个tensor变量 
2 print ( 'a is: {}'. format (a) ) #一种输出方式:{}的内容为format括号里的内容
3 print('a size is {}'.format(a.size())) #输出矩阵的维度

tensor

·其他常用方式定义tensor矩阵:

x = torch. LongTensor ( [ [2 , 3 ] [ 4 , 8 ] [7, 9] ]) #64位整型的tensor
x = torch.zeros((3, 2)) #定义(3,2)的零矩阵
x = torch.randn((3, 2)) #定义(3,2)的正态分布随机矩阵
x = torch.ones(2,2) #构建数值均为1的矩阵
x = torch.eye(3,3) #构建对角线为一的矩阵

·矩阵的数据类型转化:

a = torch. Tensor ( [ [2 , 3], [ 4 , 8], [7, 9 ] ] )
a = a.float() # 转为FloatTensor
a = a.double() # 转为DoubleTensor
a = a.short() # 转为ShortTensor
a = a.int() # 转为IntTensor
a = a.long() # 转为LongTensor

·tensor与numpy的转化(某些包(如matplotlib)只识别numpy的矩阵):

a = torch. Tensor ( [ [2 , 3], [ 4 , 8], [7, 9 ] ] ) #a为tensor型
b = np.array(a) # b为numpy型
c = torch.from_numpy(b) # c为tensor型

Variable (变量)

Variable就是变量, Variable 提供了自动求导的功能。Variable 和 Tensor 本质上没有区别,不过 Variable 会被放入一个汁算图中,然后进行前向传播,反向传播,自动求导(神经网络基本的需求)。
·自动求导:

1 # Create Varìable 
2 X = Variable(torch.Tensor( [1] ) , requires_grad=True) 
3 W = Variable(torch.Tensor( [2] ) , requires_grad=True) 
4 b = Variable(torch.Tensor( [3] ) , requires_grad=True) 
#requires_grad=True ,这个参数表示是否 对这个变量求梯度,默认的是 Fa!se ,也就是不对这个变量求梯度,这里我们希望得到 这些变量的梯度,所以需要传入这个参数。

5 Y = W * X + b   #y=2*x + 3 
6 Y.backward()   # y函数反向传递、自动求导
#x、w、b在x = 1、w = 2、b=3下的对x w b 的导数
7 print (X.grad)  #x. grad = 2 
8 print (W.grad) #w.grad = 1 
9 print (b.grad)  #b .grad =1

variable
·对矩阵求导:

x = torch.randn(3)
x = Variable(x , requires_grad = True)

y = x * 2
print(y)

y.backward(torch.tensor([1, 0.1, 0.01]))
print(x.grad)
#相当于给出了一个三维向量去做运算,这时候得到的结果 ν 就是一个向量
#这里对这个向量求导就不能直接写成 y.backward(),这样程序是会报错的。 这个时候需 要传入参数声明,比如 y.backward(torch.FloatTensor 1,1, 1) )).
#这样得到的 结果就是它们每个分量的梯度,或者可以传入 y.backward(torch.FloatTensor( [1, 0.1 , 0. 01] )) ,这样得到的梯度就是它们原本的梯度分别乘上 1 , 0.1 和 0.01。
  • 11
    点赞
  • 66
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值