1. 张量

 

1.1. 概述

 

张量(tensor)是pytorch中的一种较为基础的数据结构,类比于numpy中的ndarrays,在pytorch中,张量可以在GPU中进行运算

 

通过以下命令,我们导入pytorch和numpy:

In [1]:
import torch
import numpy as np
 

1.2. 张量初始化

 

1.2.1. 直接生成张量

In [2]:
data = [[1, 2], [3, 4]]
x_data = torch.tensor(data)
In [3]:
x_data
Out[3]:
tensor([[1, 2],
[3, 4]])
 

1.2.2. ndarrays转化

In [4]:
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
In [5]:
x_np
Out[5]:
tensor([[1, 2],
[3, 4]])
 

1.2.3. 通过已有张量生成

 

继承结构与数据类型:

In [6]:
x_ones = torch.ones_like(x_data)
In [7]:
x_ones
Out[7]:
tensor([[1, 1],
[1, 1]])
 

继承结构,改变数据类型:

In [8]:
x_rand = torch.rand_like(x_data, dtype=torch.float)
In [9]:
x_rand
Out[9]:
tensor([[0.9849, 0.3644],
[0.0800, 0.2939]])
 

1.2.4. 指定维数生成张量

 

用元组类型的数据指定维数:

In [10]:
shape = (2, 3)
 

生成张量:

In [11]:
torch.ones(shape)
Out[11]:
tensor([[1., 1., 1.],
[1., 1., 1.]])
In [12]:
torch.zeros(shape)
Out[12]:
tensor([[0., 0., 0.],
[0., 0., 0.]])
In [13]:
torch.rand(shape)
Out[13]:
tensor([[0.1744, 0.3771, 0.7969],
[0.7098, 0.9853, 0.3950]])
 

1.3. 张量属性

 

维数:

In [14]:
x_data.shape
Out[14]:
torch.Size([2, 2])
 

数据类型:

In [15]:
x_data.dtype
Out[15]:
torch.int64
 

存储设备:

In [16]:
x_data.device
Out[16]:
device(type='cpu')
 

1.4. 张量计算

 

GPU对于张量的计算更快,检测GPU是否可用:

In [17]:
torch.cuda.is_available()
Out[17]:
False
 

显然,对于笔者设备来说,由于没有显卡,GPU加速是不可用的,如果设备GPU可用,可以将CPU中的数据导入GPU:

In [18]:
if torch.cuda.is_available():
tensor = x_data.to('cuda')
 

1.4.1. 索引和切片

In [19]:
tensor = torch.ones((3, 4))
In [20]:
tensor
Out[20]:
tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])
 

类比于ndarrays,tensor也可理解为是一个多维数组,以下表示将tensor变量的第一行、第一列变为0:

In [21]:
tensor[1, 1] = 0
In [22]:
tensor
Out[22]:
tensor([[1., 1., 1., 1.],
[1., 0., 1., 1.],
[1., 1., 1., 1.]])
 

以下表示将tensor变量的第三列变为0:

In [23]:
tensor[:, 3] = 0
In [24]:
tensor
Out[24]:
tensor([[1., 1., 1., 0.],
[1., 0., 1., 0.],
[1., 1., 1., 0.]])
 

1.4.2. 张量的拼接

In [25]:
tensor1 = torch.ones((3, 4))
tensor2 = torch.zeros((3, 4))
 

使用torch.cat()方法,指定维数进行拼接:

In [26]:
torch.cat([tensor1, tensor2], dim=1)
Out[26]:
tensor([[1., 1., 1., 1., 0., 0., 0., 0.],
[1., 1., 1., 1., 0., 0., 0., 0.],
[1., 1., 1., 1., 0., 0., 0., 0.]])
In [27]:
torch.cat([tensor1, tensor2], dim=0)
Out[27]:
tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
In [28]:
torch.cat([tensor1, tensor2], dim=-1)
Out[28]:
tensor([[1., 1., 1., 1., 0., 0., 0., 0.],
[1., 1., 1., 1., 0., 0., 0., 0.],
[1., 1., 1., 1., 0., 0., 0., 0.]])
In [29]:
torch.cat([tensor1, tensor2], dim=-2)
Out[29]:
tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
In [30]:
torch.cat([tensor1, tensor2, tensor], dim=-2)
Out[30]:
tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[1., 1., 1., 0.],
[1., 0., 1., 0.],
[1., 1., 1., 0.]])
 

此处实验 dim = 2 时,有:

In [31]:
torch.cat([tensor1, tensor2], dim=2)
 
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-31-dc57fe12e880> in <module>
----> 1 torch.cat([tensor1, tensor2], dim=2) IndexError: Dimension out of range (expected to be in range of [-2, 1], but got 2)
 

根据官网示例,此处dim的取值主要是0和1:

 
x = torch.randn(2, 3)
torch.cat((x, x, x), 0)
torch.cat((x, x, x), 1)
 

综上,dim的取值有 -2、-1、0、1,然而-2、-1与0、1的意思似乎是一样的

 

1.4.3. 张量的乘积与矩阵乘法

 

逐个元素相乘:

In [32]:
tensor.mul(tensor)
Out[32]:
tensor([[1., 1., 1., 0.],
[1., 0., 1., 0.],
[1., 1., 1., 0.]])
 

等价于:

In [33]:
tensor * tensor
Out[33]:
tensor([[1., 1., 1., 0.],
[1., 0., 1., 0.],
[1., 1., 1., 0.]])
 

张量与张量的矩阵乘法:

In [34]:
tensor.matmul(tensor.T)
Out[34]:
tensor([[3., 2., 3.],
[2., 2., 2.],
[3., 2., 3.]])
 

等价于:

In [35]:
tensor @ tensor.T
Out[35]:
tensor([[3., 2., 3.],
[2., 2., 2.],
[3., 2., 3.]])
 

1.4.4. 自动赋值运算

 

自增运算:

In [36]:
tensor
Out[36]:
tensor([[1., 1., 1., 0.],
[1., 0., 1., 0.],
[1., 1., 1., 0.]])
In [37]:
tensor.add_(5)
Out[37]:
tensor([[6., 6., 6., 5.],
[6., 5., 6., 5.],
[6., 6., 6., 5.]])
In [38]:
tensor
Out[38]:
tensor([[6., 6., 6., 5.],
[6., 5., 6., 5.],
[6., 6., 6., 5.]])
 

复制运算:

In [39]:
tensor.copy_(tensor1)
Out[39]:
tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])
In [40]:
tensor
Out[40]:
tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])
 

注意:自动赋值运算可以节省内存,但是会导致一些中间过程的问题

 

1.5. Tensor与Numpy的转换

 

1.5.1. Tensor转换为Numpy

In [41]:
tensor
Out[41]:
tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])
In [42]:
np_t = tensor.numpy()
In [43]:
np_t
Out[43]:
array([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]], dtype=float32)
In [44]:
tensor.add_(5)
Out[44]:
tensor([[6., 6., 6., 6.],
[6., 6., 6., 6.],
[6., 6., 6., 6.]])
In [45]:
np_t
Out[45]:
array([[6., 6., 6., 6.],
[6., 6., 6., 6.],
[6., 6., 6., 6.]], dtype=float32)
 

可见:Tensor和Numpy共用内存,一个改变时另一个也改变

 

1.5.2. Numpy转Tensor

In [46]:
np_t
Out[46]:
array([[6., 6., 6., 6.],
[6., 6., 6., 6.],
[6., 6., 6., 6.]], dtype=float32)
In [47]:
tensor
Out[47]:
tensor([[6., 6., 6., 6.],
[6., 6., 6., 6.],
[6., 6., 6., 6.]])
In [48]:
t_np = torch.from_numpy(np_t)
In [49]:
t_np
Out[49]:
tensor([[6., 6., 6., 6.],
[6., 6., 6., 6.],
[6., 6., 6., 6.]])
In [50]:
np.add(np_t, 1, out=np_t)
Out[50]:
array([[7., 7., 7., 7.],
[7., 7., 7., 7.],
[7., 7., 7., 7.]], dtype=float32)
In [51]:
t_np
Out[51]:
tensor([[7., 7., 7., 7.],
[7., 7., 7., 7.],
[7., 7., 7., 7.]])
In [52]:
np.add(np_t, 1)
Out[52]:
array([[8., 8., 8., 8.],
[8., 8., 8., 8.],
[8., 8., 8., 8.]], dtype=float32)
In [53]:
t_np
Out[53]:
tensor([[7., 7., 7., 7.],
[7., 7., 7., 7.],
[7., 7., 7., 7.]])
 

可见:np.add()指定out=时才会重新赋值

 

1.6. 参考资料:

pytorch学习笔记一之张量的更多相关文章

  1. [PyTorch 学习笔记] 1.3 张量操作与线性回归

    本章代码:https://github.com/zhangxiann/PyTorch_Practice/blob/master/lesson1/linear_regression.py 张量的操作 拼 ...

  2. [PyTorch 学习笔记] 1.2 Tensor(张量)介绍

    本章代码: https://github.com/zhangxiann/PyTorch_Practice/blob/master/lesson1/tensor_introduce1.py https: ...

  3. Pytorch学习笔记(二)---- 神经网络搭建

    记录如何用Pytorch搭建LeNet-5,大体步骤包括:网络的搭建->前向传播->定义Loss和Optimizer->训练 # -*- coding: utf-8 -*- # Al ...

  4. Pytorch学习笔记(一)---- 基础语法

    书上内容太多太杂,看完容易忘记,特此记录方便日后查看,所有基础语法以代码形式呈现,代码和注释均来源与书本和案例的整理. # -*- coding: utf-8 -*- # All codes and ...

  5. 【pytorch】pytorch学习笔记(一)

    原文地址:https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html 什么是pytorch? pytorch是一个基于p ...

  6. [PyTorch 学习笔记] 1.4 计算图与动态图机制

    本章代码:https://github.com/zhangxiann/PyTorch_Practice/blob/master/lesson1/computational_graph.py 计算图 深 ...

  7. [PyTorch 学习笔记] 2.2 图片预处理 transforms 模块机制

    PyTorch 的数据增强 我们在安装PyTorch时,还安装了torchvision,这是一个计算机视觉工具包.有 3 个主要的模块: torchvision.transforms: 里面包括常用的 ...

  8. [PyTorch 学习笔记] 4.3 优化器

    本章代码: https://github.com/zhangxiann/PyTorch_Practice/blob/master/lesson4/optimizer_methods.py https: ...

  9. 【深度学习】Pytorch 学习笔记

    目录 Pytorch Leture 05: Linear Rregression in the Pytorch Way Logistic Regression 逻辑回归 - 二分类 Lecture07 ...

  10. Pytorch学习笔记(二)——Tensor

    一.对Tensor的操作 从接口的角度讲,对Tensor的操作可以分为两类: (1)torch.function (2)tensor.function 比如torch.sum(a, b)实际上和a.s ...

随机推荐

  1. USB口3A限流保护芯片。带短路保护

    一般说明 PW1503是超低RDS(ON)开关,具有可编程的电流限制,以保护电源源于过电流和短路情况.它具有超温保护以及反向闭锁功能. PW1503采用薄型(1毫米)5针薄型SOT封装,提供可调版本. ...

  2. HMS Core 6.8.0版本发布公告

    分析服务 ◆ 游戏行业新增"区服分析"埋点模板及分析报告,支持开发者分服务器查看用户付费.留存等指标,可进一步评估不同服务器的玩家质量: ◆ 新增营销活动报告,可查看广告任务带来的 ...

  3. SpringBoot内置tomcat启动过程及原理

    作者:李岩科 1 背景 SpringBoot 是一个框架,一种全新的编程规范,他的产生简化了框架的使用,同时也提供了很多便捷的功能,比如内置 tomcat 就是其中一项,他让我们省去了搭建 tomca ...

  4. ModuleNotFoundError: No module named 'MySQLdb'

    执行命令 python manage.py makemigrations时抛出以下错误 Traceback (most recent call last): File "D:\Program ...

  5. vue后退页面刷新数据和缓存数据

    我们在项目中经常使用this.$router.go(-1)  但是,有时我们需要把前一个页面的数据进行缓存,有时需要刷新数据,下面来记录一下怎么操作吧 首先:在vue项目中缓存页面我们能想到 keep ...

  6. Redis基本操作(2)

    一.list类型 列表的元素类型为string 按照插⼊顺序排序 增加.修改 例1:在左侧插⼊数据 lpush key value1 value2 ... 例2:在右侧插⼊数据 rpush key v ...

  7. [OpenCV实战]33 使用OpenCV进行Hough变换

    目录 1 什么是霍夫变换 1.1 应用霍夫变换以检测图像中的线条 1.2 累加器 1.3 线条检测 1.4 圆环的检测 2 代码 3 参考 1 什么是霍夫变换 霍夫变换是用于检测图像中的简单形状(诸如 ...

  8. ubunut安装qtcreater

    安装gcc 1 kxb@kxb:~$ gcc -v 2 3 Command 'gcc' not found, but can be installed with: 4 5 sudo apt insta ...

  9. CVE-2020-1957

    漏洞名称 Apache Shiro 认证绕过漏洞 CVE-2020-1957 利用条件 Apache Shiro < 1.5.1 漏洞原理 Apache Shiro 是一款开源安全框架,提供身份 ...

  10. python之路50 ORM执行SQL语句 操作多表查询 双下线方法

    ORM执行查询SQL语句 有时候ORM的操作效率可能偏低 我们是可以自己编写SQL的 方式1: models.User.objects.raw('select * from app01_user;') ...