pytorch基础教程

基础部分

基本数据类型

Data type

在这里插入图片描述
在这里插入图片描述常用的有torch.FloatTensor, torch.DoubleTensor, torch.IntTensor, torch.ByteTensor, torch.LongTensor。

如何标注string呢?
在pytorch中使用One-hot(独热编码)来表示string,[0.1.0.0…],比如:

[1 0]:猫
[0 1]:狗

但是词与词之间的相关性并没有在one-hot中显现。所以进一步要(Embedding)用编码的方法表达语言:比如使用word2vec和glove等。

import torch
a = torch.randn(2,3) #随机初始化一个两行三列的符合正态分布的矩阵
a.type()
#'torch.FloatTensor'
isinstance(a,torch.FloatTensor)
#True

维度dim

标量:Dimension 0
Loss就是典型dimension为零的标量

torch.tensor(1.3)
# 1.3是零维,但[1.3]是一维,长度为1的Tensor
a =torch.tensor(2.2)
a.shape,a.size(),a.dim()
# torch.Size([])

Dimension 1
Bias就是dimension为1的tensor
linear input就是dimension为1的tensor

torch.tensor([1.1,2.2]).shape
# torch.Size([2]) 一维
torch.FloatTensor(2) # dim=1 size=2
# tensor([4.2981e+21, 6.3828e+28])

Dimension 2
linear input batch就是dimension为2的tensor,比如:
每张图片像素 28*28 ,拉平–>[784]
n张照片
[n,784]

#.FloatTensor接受的是数据的shape
a = torch.FloatTensor(2,2)
'''
tensor([[2.0000e+00, 2.0000e+00],
        [6.0020e-28, 1.0842e-19]])
'''
a = torch.randn(2,3)
a.shape
# torch.Size([2, 3])
a.size(0)
# 2
a.size(1)
# 3
a.shape[0]
# 2

Dimension 3
RNN input Batch就是dimension为3的tensor,比如:
20句sentences,每个sentence中有10个单词,每个单词用one-hot编码,100维向量。
[10,20,100]

a = torch.rand(1,2,3) #随机均匀分布 
'''
tensor([[[0.3725, 0.7952, 0.4332],
         [0.2388, 0.7563, 0.8000]]])
'''
a.shape
# torch.Size([1, 2, 3])
a[0] #输出是二维
'''
tensor([[0.3725, 0.7952, 0.4332],
        [0.2388, 0.7563, 0.8000]])
'''
a[0,0]  #输出是一维
# tensor([0.3725, 0.7952, 0.4332])
a[0,0,0]  #输出是零维
# tensor(0.3725)

Dimension 4
CNN就是dimension为4的tensor
[b,c,h,w]
batch,channel,height,weight

a = torch.rand(2,1,28,28) #2 张图片 1灰度通道(3:RGB通道) h:28 * w:28

numel:是指tensor占用内存的数量 number of elements

a.numel()
# 1568
a.dim()
# 4

创建Tensor

  • import from numpy
# 从numpy引入
import numpy as np
data = np.ones(2)
torch.from_numpy(data)
# tensor([1., 1.], dtype=torch.float64)
  • import from list
torch.tensor([2,3.2])
# tensor([2.0000, 3.2000])
  • 生成数据

生成未初始化的数据

torch.empty(2,3)
'''
tensor([[0.0000e+00, 2.0000e+00, 1.8754e+28],
        [4.0611e-08, 0.0000e+00, 0.0000e+00]])
'''
torch.FloatTensor(2,3) #推荐使用
'''
tensor([[1.1210e-44, 0.0000e+00, 0.0000e+00],
        [0.0000e+00, 0.0000e+00, 0.0000e+00]])
'''
#未初始化的tensor一定要跟写入数据的后续步骤,因为未初始化的数据很随机,会对数据分析产生误差

随机初始化:rand/rand_like,randint,randn

# rand会随机产生0-1之间的数值,不包括1 [min,max)
a = torch.rand(3,3)
'''
tensor([[0.5007, 0.2791, 0.4723],
        [0.9040, 0.7485, 0.9240],
        [0.4613, 0.3655, 0.4356]])
'''
#torch.rand_like(a),继承a的shape
torch.rand_like(a)
'''
tensor([[0.9106, 0.1066, 0.4969],
        [0.7428, 0.6734, 0.8423],
        [0.6036, 0.9512, 0.8968]])
'''
#((start,end),shape)
torch.randint(1,10,(2,3))
'''
tensor([[2, 4, 7],
        [6, 7, 2]])
'''
#randint只能采整数,如果采0-10之间的tensor
torch.rand_like(a)*10 #0-100之间,*100
'''
tensor([[5.5882, 2.2705, 9.5224],
        [2.7068, 3.5601, 8.8855],
        [7.1446, 2.3037, 0.1559]])
'''
# randn 随机正态分布,推荐使用
torch.randn(3,3)
'''
tensor([[ 0.4730,  1.0773,  1.0708],
        [-0.0661, -0.7352,  0.9882],
        [ 0.5452, -1.3483, -0.5176]])
'''
# 指定分布,不常用
# 均值都为0,标准差1,0.9,..0.1
torch.normal(mean = torch.full([10],0),std = torch.arange(1,0,-0.1))

linspace logspace

torch.linspace(0,10,steps=4) #[0,10] n为4的等差数列
# tensor([ 0.0000,  3.3333,  6.6667, 10.0000])
torch.linspace(0,10,steps=11)
# tensor([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.])
torch.logspace(0,-1,steps =10)
# tensor([1.0000, 0.7743, 0.5995, 0.4642, 0.3594, 0.2783, 0.2154, 0.1668, 0.1292,0.1000])
# logspace的base参数可以设置为2,10,e等底数
torch.logspace(0,-1,steps =10,base =2)
# tensor([1.0000, 0.9259, 0.8572, 0.7937, 0.7349, 0.6804, 0.6300, 0.5833, 0.5400, 0.5000])

ones/zeros/eye

#ones/zeros/eye
torch.ones(3,3)
torch.eye(3,3)
torch.zeros(3,3)

randperm:random.shuffle

torch.randperm(10)
# tensor([3, 4, 8, 2, 5, 0, 9, 6, 7, 1])
在这里插入代码片a = torch.rand(2,3)
'''
tensor([[0.3221, 0.1189, 0.6717],
        [0.5141, 0.1630, 0.4550]])
'''
b = torch.rand(2,2)
'''
tensor([[0.8794, 0.7519],
        [0.4448, 0.9401]])
'''
idx = torch.randperm(2)
idx
# tensor([1, 0])
a[idx] # 第二行和第一行交换位置
'''
tensor([[0.5141, 0.1630, 0.4550],
        [0.3221, 0.1189, 0.6717]])
'''
b[idx]
'''
tensor([[0.4448, 0.9401],
        [0.8794, 0.7519]])
'''

set default type

torch.tensor([1.2,2]).type()
# 'torch.DoubleTensor'
torch.set_default_tensor_type(torch.FloatTensor)
torch.tensor([1.2,2]).type()
# 'torch.FloatTensor'
# 增强学习一般使用double,其他一般使用float

索引和切片

indexing

import torch
a = torch.rand(4,3,28,28)
a[0].shape
# torch.Size([3, 28, 28])
a[0,0].shape
# torch.Size([28, 28])
a[0,0,2,4]
# tensor(0.7394)

select first/last N

在这里插入代码片a.shape
# torch.Size([4, 3, 28, 28])
a[:2].shape
# torch.Size([2, 3, 28, 28])
a[:2,:1,:,:].shape
# torch.Size([2, 1, 28, 28])
a[:2,1:,:,:].shape
# torch.Size([2, 2, 28, 28])
a[:2,-1:,:,:].shape
# torch.Size([2, 1, 28, 28])

select by steps
start:end:step

a[:,:,0:28:2,0:28:2].shape
# torch.Size([4, 3, 14, 14])
# 0:28 相当于 0:28:1
a[:,:,::2,::2].shape
torch.Size([4, 3, 14, 14])

select by specific index

a.shape
# torch.Size([4, 3, 28, 28])
# 第0个维度,第0张图片和第2张图片
a.index_select(0,torch.tensor([0,2])).shape 
# torch.Size([2, 3, 28, 28])
a.index_select(1,torch.tensor([1,2])).shape
# torch.Size([4, 2, 28, 28])
a.index_select(2,torch.arange(8)).shape
# torch.Size([4, 3, 8, 28])

--> 任意多的维度

a[...].shape #任意多的维度
# torch.Size([4, 3, 28, 28])
a[3,...].shape
# torch.Size([3, 28, 28])
a[:,1,...].shape
# torch.Size([4, 28, 28]) 
a[...,:2].shape
# torch.Size([4, 3, 28, 2])

select by mask

x = torch.randn(3,4)
mask = x.ge(0.5)# >0.5=True,<0.5=False
torch.masked_select(x,mask)
# tensor([0.8901, 2.3088, 2.3641, 1.1609, 1.1885])

select by flatten index

# take先将所有的tensor打平,再索引
src = torch.tensor([[4,3,5],[6,7,8]])
torch.take(src,torch.tensor([0,2,5]))
# tensor([4, 5, 8])

Tensor维度变换

view/reshape

a = torch.rand(4,1,28,28)
#保证numel一致即可
a.view(4,1*28*28).shape #适合全连接层
# torch.Size([4, 784])
a.view(4*1*28,28).shape 
# torch.Size([112, 28])
a.view(4*1,28,28).shape 
# torch.Size([4, 28, 28])

# 数据存储/维度顺序非常重要
b = a.view(4,784) 
b.view(4,28,28,1) # Logic bug,会造成数据污染

squeeze/unsqueeze
unsqueeze 增维

a.shape
# torch.Size([4, 1, 28, 28])
#(0) 4 (1) 1 (2) 28 (3) 28 (4/-1)
a.unsqueeze(0).shape # 0位置insert dim 1
# torch.Size([1, 4, 1, 28, 28])
a.unsqueeze(-1).shape # -1位置insert dim 1
# torch.Size([4, 1, 28, 28, 1])
a.unsqueeze(4).shape
# torch.Size([4, 1, 28, 28, 1])
a = torch.tensor([1.2,1.6]) 
a.shape
# torch.Size([2])
a.unsqueeze(-1).shape
# torch.Size([2, 1])
a.unsqueeze(-1)
'''
tensor([[1.2000],
        [1.6000]])

'''
a.unsqueeze(0)
# tensor([[1.2000, 1.6000]])
#图片处理
import torch
b = torch.rand(32) # bias
f = torch.rand(4,32,14,14) 
#给每个channel上的所有像素增加一个偏置bias,size保持一致
#将f叠加在b上面,将b变为四维
b = b.unsqueeze(0).unsqueeze(2).unsqueeze(3)
b.shape
#torch.Size([1, 32, 1, 1])
#再扩张成[4,32,14,14]就可以叠加了

squeeze减维

#只能挤压size为1的维度
b.shape
# torch.Size([1, 32, 1, 1])
b.squeeze().shape #能挤压的全部挤压
# torch.Size([32])
b.squeeze(0).shape,b.squeeze(-4).shape
# torch.Size([32, 1, 1])
b.squeeze(-1).shape
# torch.Size([1, 32, 1])
b.squeeze(1).shape 
#挤压第1维度,size是32,不是1,不能挤压,维持不变
# torch.Size([1, 32, 1, 1])

Expand:更节省内存/repeat:浪费内存

b.shape
# torch.Size([1, 32, 1, 1])
a = torch.rand(4,32,14,14)
#只有1可以expand到4或14,其他不可以
b.expand(4,32,14,14).shape 
# torch.Size([4, 32, 14, 14])

#-1表示保持不变
b.expand(-1,32,-1,-1).shape
# torch.Size([1, 32, 1, 1])

#repeat参数是拷贝次数
b.repeat(4,1,14,14).shape 
# torch.Size([4, 32, 14, 14])

transpose/.t/permute
转置操作.t:只适用于2维

a = torch.randn(3,4)#只适用于2维
a.t()
'''
tensor([[ 0.4086,  0.6512,  0.3118],
        [-1.3944, -0.1756, -2.9389],
        [-1.1064,  1.3543, -1.1606],
        [ 1.9239, -0.8880,  0.9098]])
'''

交换维度:transpose()

a = torch.randn(4,3,28,28)
# dim1和dim3交换,原来的存储顺序改变,变成了不连续的数据
a1 = a.transpose(1,3) 
a1.shape
# torch.Size([4, 28, 28, 3])

#维度交换后先将数据转化为连续
a1 = a.transpose(1,3).contiguous().view(4,3*28*28).view(4,3,28,28)
a1.shape
# torch.Size([4, 3, 28, 28])
# b c h w--> b w h c !--> b c h w 此次还原的顺序是错误的,数据污染。

torch.all(torch.eq(a,a1))
# tensor(False)
# a 和 a1不同

a2 = a.transpose(1,3).contiguous().view(4,3*28*28).view(4,28,28,3).transpose(1,3)
#b c h w-->b w h c-->b w h c--> b c h w
a2.shape
# torch.Size([4, 3, 28, 28])
torch.all(torch.eq(a,a2))
# tensor(True)
#a 和 a2 相同

# 维度顺序一定要人为跟踪

permute:多维转置

b = torch.rand(4,3,28,32)
b.transpose(1,3).transpose(1,2).shape
# torch.Size([4, 28, 32, 3])
b.permute(0,2,3,1).shape
# torch.Size([4, 28, 32, 3])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值