Deep Learning with Pytorch 中文简明笔记 第三章 It starts with a tensor

Deep Learning with Pytorch 中文简明笔记 第三章 Tensor

Pytorch作为深度学习框架的后起之秀,凭借其简单的API和简洁的文档,收到了越来越多人的关注和喜爱。本文主要总结了 Deep Learning with Pytorch 一书第三章[It starts with a tensor]的主要内容,并加以简单明了的解释,作为自己的学习记录,也供大家学习和参考。

1. 主要内容

本章内容主要包括

  1. Pytorch中最基本的数据结构Tensor
  2. Tensor的索引操作
  3. 和numpy多维向量交互
  4. 将Tensor放入GPU中以加速运算

2. 多维向量Tensor

# In[1]:
a = [1.0, 2.0, 1.0]

# In[2]:
a[0]

# Out[2]: 
1.0

# In[3]: 
a[2] = 3.0

# Out[3]: 
[1.0, 2.0, 3.0]

# In[4]: 
import torch 
a = torch.ones(3)

# Out[4]: 
tensor([1., 1., 1.])

# In[5]: 
a[1]

# Out[5]: 
tensor(1.)

# In[6]: 
float(a[1])

# Out[6]: 
1.0

# In[7]:
a[2] = 2.0 
a

# Out[7]: 
tensor([1., 1., 2.])

在Pytorch中,可以直接使用Python原生的list直接构建Tensor对象。但是对于Python的list是对list所包含对象的收集,这些对象在内存中可能不是连续的(一般情况下均不连续)。但是Pytorch中的Tensor或者numpy则是内存中连续分配的C语言被解包的数字类型,外加一些元数据(如矩阵的维度,数据类型等信息)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zZzgFdp1-1595349999288)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/7839a2e8-646a-49cd-913f-e26d28497eac/Untitled.png)]

# In[12]: 
points.shape

# Out[12]: 
torch.Size([3, 2])

# In[13]: 
points = torch.zeros(3, 2) 
points

# Out[13]: 
tensor([[0., 0.], [0., 0.], [0., 0.]])

通过shape来访问Tensor的形状,通过zeros或者ones来初始化指定大小的Tensor

3. Tensor的索引操作

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kRQwEFHp-1595349999290)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/5f231ba0-1772-4a65-ae7d-29f094635eb4/Untitled.png)]

值得注意的是,points[None]会在最后增加一个维度

import torch

a = torch.tensor(1)
print(a.shape)
a = a[None]
print(a.shape)
a = a[None]
print(a.shape)

输出为

torch.Size([])
torch.Size([1])
torch.Size([1, 1])

4. Tensor维度命名

通常来讲,对于多维张量来说,每个维度都有其含义,如图片的RBG通道,图片的高宽或者是mini batch的size。Pytorch支持为张量的不同维度命名,一方面使代码更可读,另一方面减少出错的可能性。

# In[2]: 
img_t = torch.randn(3, 5, 5) # shape [channels, rows, columns] 
weights = torch.tensor([0.2126, 0.7152, 0.0722])

# In[3]:
batch_t = torch.randn(2, 3, 5, 5) # shape [batch, channels, rows, columns]

# In[4]: 
img_gray_naive = img_t.mean(-3) # 表示对倒数第3个维度进行规约平均
batch_gray_naive = batch_t.mean(-3) 
img_gray_naive.shape, batch_gray_naive.shape

# Out[4]: 
(torch.Size([5, 5]), torch.Size([2, 5, 5]))

在创建Tensor的时候,可以使用names属性进行命名

# In[7]: 
weights_named = torch.tensor([0.2126, 0.7152, 0.0722], names=['channels'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值