PyTorch | (1)初识PyTorch

PyTorch | (2)PyTorch 入门-张量

PyTorch | (3)Tensor及其基本操作


Tensor attributes:

在tensor attributes中有三个类,分别为torch.dtype, torch.device, 和 torch.layout

其中, torch.dtype 是展示 torch.Tensor 数据类型的类,pytorch 有八个不同的数据类型,下表是完整的 dtype 列表.


Torch.device 是表现 torch.Tensor被分配的设备类型的类,其中分为’cpu’ 和 ‘cuda’两种,如果设备序号没有显示则表示此 tensor 被分配到当前设备, 比如: 'cuda' 等同于 'cuda': X , X 为torch.cuda.current _device() 返回值

我们可以通过 tensor.device 来获取其属性,同时可以利用字符或字符+序号的方式来分配设备

通过字符串

torch.device('cuda:0')

运行结果:

device(type='cuda', index=0)

torch.device('cpu')

运行结果:
device(type='cpu')

torch.device('cuda') # 当前设备

运行结果:
device(type='cuda')

通过字符串和设备序号

torch.device('cuda', 0)

运行结果:

device(type='cuda', index=0)

torch.device('cpu', 0)

运行结果:
device(type='cpu', index=0)


此外,cpu 和 cuda 设备的转换使用 'to' 来实现:

device_cpu = torch.device("cuda")  #声明cuda设备
device_cuda = torch.device('cuda')  #设备cpu设备
data = torch.Tensor([1])
data.to(device_cpu)  #将数据转为cpu格式
data.to(device_cuda)   #将数据转为cuda格式

torch.layout 是表现 torch.Tensor 内存分布的类,目前只支持 torch.strided


创建tensor

  • 直接创建

torch.tensor(data, dtype=None, device=None,requires_grad=False)

data - 可以是list, tuple, numpy array, scalar或其他类型

dtype - 可以返回想要的tensor类型

device - 可以指定返回的设备

requires_grad - 可以指定是否进行记录图的操作,默认为False

需要注意的是,torch.tensor 总是会复制 data, 如果你想避免复制,可以使 torch.Tensor. detach(),如果是从 numpy 中获得数据,那么你可以用 torch.from_numpy(), 注from_numpy() 是共享内存的

torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])

运行结果:

tensor([[ 0.1000,  1.2000],[ 2.2000,  3.1000],[ 4.9000,  5.2000]])
torch.tensor([0, 1])  # Type inference on data 

运行结果:

tensor([ 0,  1])
torch.tensor([[0.11111, 0.222222, 0.3333333]],dtype=torch.float64,device=torch.device('cuda:0'))  # creates a torch.cuda.DoubleTensor

运行结果:

tensor([[ 0.1111,  0.2222,  0.3333]], dtype=torch.float64, device='cuda:0')
torch.tensor(3.14159)  # Create a scalar (zero-dimensional tensor)

运行结果:

tensor(3.1416)
torch.tensor([])  # Create an empty tensor (of size (0,))

运行结果:

tensor([])
  • 从numpy中获得数据

torch.from_numpy(ndarry)

注:生成返回的tensor会和ndarry共享数据,任何对tensor的操作都会影响到ndarry,
反之亦然

>>> a = numpy.array([1, 2, 3])
>>> t = torch.from_numpy(a)
>>> t
tensor([ 1,  2,  3])
>>> t[0] = -1
>>> a
array([-1,  2,  3])
  • 创建特定的tensor

根据数值要求:

torch.zeros(*sizes, out=None, ..)# 返回大小为sizes的零矩阵 torch.zeros_like(input, ..) # 返回与input相同size的零矩阵torch.ones(*sizes, out=None, ..) #f返回大小为sizes的单位矩阵torch.ones_like(input, ..) #返回与input相同size的单位矩阵torch.full(size, fill_value, …) #返回大小为sizes,单位值为fill_value的矩阵torch.full_like(input, fill_value, …) 返回与input相同size,单位值为fill_value的矩阵torch.arange(start=0, end, step=1, …) #返回从start到end, 单位步长为step的1-d tensor.torch.linspace(start, end, steps=100, …)  #返回从start到end, 间隔中的插值数目为steps的1-d tensortorch.logspace(start, end, steps=100, …) #返回1-d tensor ,从10^start到10^end的steps个对数间隔

根据矩阵要求:

torch.eye(n, m=None, out=None,…) #返回2-D 的单位对角矩阵torch.empty(*sizes, out=None, …) #返回被未初始化的数值填充,大小为sizes的tensortorch.empty_like(input, …) # 返回与input相同size,并被未初始化的数值填充的tensor
  • 随机采用生成:

torch.normal(mean, std, out=None)torch.rand(*size, out=None, dtype=None, …) #返回[0,1]之间均匀分布的随机数值torch.rand_like(input, dtype=None, …) #返回与input相同size的tensor, 填充均匀分布的随机数值torch.randint(low=0, high, size,…) #返回均匀分布的[low,high]之间的整数随机值torch.randint_like(input, low=0, high, dtype=None, …) #torch.randn(*sizes, out=None, …) #返回大小为size,由均值为0,方差为1的正态分布的随机数值torch.randn_like(input, dtype=None, …)torch.randperm(n, out=None, dtype=torch.int64) # 返回0到n-1的数列的随机排列

张量的操作

  索引: 支持numpy的常用索引和切片操作

  加法:和numpy类似的广播原则

#索引操作
y = torch.rand(5,3)
y[1:, 2]  #切片和索引
y[y>0.5] #花式索引#加法操作(和numpy一样的广播原则)
result = x+y
reslut = torch.add(x, y)
y.add_(x)  #直接对y的值进行修改,
(以_结尾的方法会直接在原地修改变量, 如x.copy_(y), x.t_()会修改x.)result = torch.empty(5,3)
torch.add(x, y, out=result)  #这里的result必须先定义#对于一个元素的张量,可以直接通过x.item()拿到元素值
x = torch.ones(3,4)
y = torch.sum(x)
print(y.item(0))     #得到整数12.0

cuda Tensor: pytorch 支持Gpu操作,可以在Gpu上创建tensor,通过to()方法可以在cpu和Gpu上间转换tensor

if torch.cuda.is_available():device = torch.device("cuda")y = torch.ones_like(x, device=device)   #直接在Gpu上创建tensorx = x.to(device)  #从cpu上转移到gpuz = x+yprint(z.to("cpu", torch.double))  #转回到cpu,并改变数据类型
  • 点对点操作

三角函数:

torch.abs(input, out=None)
torch.acos(input, out=None)
torch.asin(input, out=None)
torch.atan(input, out=None)
torch.atan2(input, inpu2, out=None)
torch.cos(input, out=None)
torch.cosh(input, out=None)
torch.sin(input, out=None)
torch.sinh(input, out=None)
torch.tan(input, out=None)
torch.tanh(input, out=None)

基本运算,加减乘除

Torch.add(input, value, out=None).add(input, value=1, other, out=None).addcdiv(tensor, value=1, tensor1, tensor2, out=None).addcmul(tensor, value=1, tensor1, tensor2, out=None)
torch.div(input, value, out=None).div(input, other, out=None)
torch.mul(input, value, out=None).mul(input, other, out=None)

对数运算:

torch.log(input, out=None)  # y_i=log_e(x_i)
torch.log1p(input, out=None)  #y_i=log_e(x_i+1)
torch.log2(input, out=None)   #y_i=log_2(x_i)
torch.log10(input,out=None)  #y_i=log_10(x_i)

幂函数:

torch.pow(input, exponent, out=None)  # y_i=input^(exponent)

指数运算

torch.exp(tensor, out=None)    #y_i=e^(x_i)
torch.expm1(tensor, out=None)   #y_i=e^(x_i) -1

截断函数

torch.ceil(input, out=None)   #返回向正方向取得最小整数
torch.floor(input, out=None)  #返回向负方向取得最大整数torch.round(input, out=None)  #返回相邻最近的整数,四舍五入torch.trunc(input, out=None)  #返回整数部分数值
torch.frac(tensor, out=None)  #返回小数部分数值torch.fmod(input, divisor, out=None)  #返回input/divisor的余数
torch.remainder(input, divisor, out=None)  #同上

其他运算

torch.erf(tensor, out=None)torch.erfinv(tensor, out=None)torch.sigmoid(input, out=None)torch.clamp(input, min, max out=None)  #返回 input<min,则返回min, input>max,则返回max,其余返回inputtorch.neg(input, out=None) #out_i=-1*(input)torch.reciprocal(input, out=None)  # out_i= 1/input_itorch.sqrt(input, out=None)  # out_i=sqrt(input_i)
torch.rsqrt(input, out=None) #out_i=1/(sqrt(input_i))torch.sign(input, out=None)  #out_i=sin(input_i)  大于0为1,小于0为-1torch.lerp(start, end, weight, out=None)
  • 降维操作

torch.argmax(input, dim=None, keepdim=False) #返回最大值排序的索引值
torch.argmin(input, dim=None, keepdim=False)  #返回最小值排序的索引值torch.cumprod(input, dim, out=None)  #y_i=x_1 * x_2 * x_3 *…* x_i
torch.cumsum(input, dim, out=None)  #y_i=x_1 + x_2 + … + x_itorch.dist(input, out, p=2)       #返回input和out的p式距离
torch.mean()                      #返回平均值
torch.sum()                       #返回总和
torch.median(input)               #返回中间值
torch.mode(input)                 #返回众数值
torch.unique(input, sorted=False) #返回1-D的唯一的tensor,每个数值返回一次.
>>> output = torch.unique(torch.tensor([1, 3, 2, 3], dtype=torch.long))
>>> output
tensor([ 2,  3,  1])torch.std(  #返回标准差)
torch.var() #返回方差torch.norm(input, p=2) #返回p-norm的范式
torch.prod(input, dim, keepdim=False) #返回指定维度每一行的乘积
  • 对比操作:

torch.eq(input, other, out=None)  #按成员进行等式操作,相同返回1
torch.equal(tensor1, tensor2) #如果tensor1和tensor2有相同的size和elements,则为true
>>> torch.eq(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]]))
tensor([[ 1,  0],[ 0,  1]], dtype=torch.uint8)
>>> torch.eq(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]]))
tensor([[ 1,  0],[ 0,  1]], dtype=torch.uint8)torch.ge(input, other, out=None)   # input>= other
torch.gt(input, other, out=None)   # input>other
torch.le(input, other, out=None)    # input=<other
torch.lt(input, other, out=None)    # input<other
torch.ne(input, other, out=None)  # input != other 不等于torch.max()                        # 返回最大值
torch.min()                        # 返回最小值
torch.isnan(tensor) #判断是否为’nan’
torch.sort(input, dim=None, descending=False, out=None) #对目标input进行排序
torch.topk(input, k, dim=None, largest=True, sorted=True, out=None)  #沿着指定维度返回最大k个数值及其索引值
torch.kthvalue(input, k, dim=None, deepdim=False, out=None) #沿着指定维度返回最小k个数值及其索引值
  • 频谱操作

torch.fft(input, signal_ndim, normalized=False)
torch.ifft(input, signal_ndim, normalized=False)
torch.rfft(input, signal_ndim, normalized=False, onesided=True)
torch.irfft(input, signal_ndim, normalized=False, onesided=True)
torch.stft(signa, frame_length, hop, …)
  • 其他操作:

torch.cross(input, other, dim=-1, out=None)  #叉乘(外积)torch.dot(tensor1, tensor2)  #返回tensor1和tensor2的点乘torch.mm(mat1, mat2, out=None) #返回矩阵mat1和mat2的乘积torch.eig(a, eigenvectors=False, out=None) #返回矩阵a的特征值/特征向量 torch.det(A)  #返回矩阵A的行列式torch.trace(input) #返回2-d 矩阵的迹(对对角元素求和)torch.diag(input, diagonal=0, out=None) #torch.histc(input, bins=100, min=0, max=0, out=None) #计算input的直方图torch.tril(input, diagonal=0, out=None)  #返回矩阵的下三角矩阵,其他为0torch.triu(input, diagonal=0, out=None) #返回矩阵的上三角矩阵,其他为0

参考资料

1. https://zhuanlan.zhihu.com/p/36233589

2. https://www.cnblogs.com/silence-cho/p/11404817.html

PyTorch | (3)Tensor及其基本操作相关推荐

  1. pytorch方法,Tensor及其基本操作_重点

    由于之前的草稿都没了,现在只有重写-. 我好痛苦 本章只是对pytorch的常规操作进行一个总结,大家看过有脑子里有印象就好,知道有这么个东西,需要的时候可以再去详细的看,另外也还是需要在实战中多运用 ...

  2. pytorch Tensor及其基本操作

    转自: https://zhuanlan.zhihu.com/p/36233589 由于之前的草稿都没了,现在只有重写-. 我好痛苦 本章只是对pytorch的常规操作进行一个总结,大家看过有脑子里有 ...

  3. 【Pytorch】Tensor基本操作

    [Pytorch]Tensor基本操作 一.Tensor概述 二.Tensor张量的定义 tensor基本定义 获取tensor大小 三.生成Tensor 定义全0的tensor 定义随机tensor ...

  4. tch-rs指南 - Tensor的基本操作

    文章目录 1 概述 2 Tensor的基本操作 2.1 Tensor的初始化 (1)通过数组创建 (2)通过默认方法创建 (3)通过其他的`tensor`创建 (4)通过`opencv::core:: ...

  5. Pytorch张量tensor的使用

    1. 张量Tensor Tensors张量: 张量的概念类似于Numpy中的ndarray数据结构, 最大的区别在于Tensor可以利用GPU的加速功能. 张量是一个统称,其中包含很多类型:   [各 ...

  6. Pytorch List Tensor转Tensor,,reshape拼接等操作

    Pytorch List Tensor转Tensor,reshape拼接等操作 持续更新一些常用的Tensor操作,比如List,Numpy,Tensor之间的转换,Tensor的拼接,维度的变换等操 ...

  7. pytorch tensor查找0_在PyTorch中Tensor的查找和筛选例子

    本文源码基于版本1.0,交互界面基于0.4.1 import torch 按照指定轴上的坐标进行过滤 index_select() 沿着某tensor的一个轴dim筛选若干个坐标 >>&g ...

  8. pytorch 入门Tensor(一)

    Tensor Tensor张量,可简单地认为它就是一个数组,且支持高效的科学计算.它可以是一个数(标量).一维数组(向量).二维数组(矩阵)和更高维的数组(高阶数据).Tensor和Numpy的nda ...

  9. python代码转换为pytorch_python基础教程Pytorch之Tensor和Numpy之间的转换的实现方法...

    为什么要相互转换: 1. 要对tensor进行操作,需要先启动一个Session,否则,我们无法对一个tensor比如一个tensor常量重新赋值或是做一些判断操作,所以如果将它转化为numpy数组就 ...

最新文章

  1. 新手也能立即上手,用Python90多行代码画出“樱花园”仙境(源码+注释)
  2. Kernel 社区 开发准备工作mutt 邮件使用
  3. asm冗余 oracle_oracle asm 磁盘管理什么场景该用什么样的冗余方式
  4. you may be a victim of software counterfeiting 的解药(亲自验证过方法2)
  5. C和C++中的默认类型
  6. lastpass安卓最新版_LastPass
  7. Spring 基于注解(annotation)的配置之@Required注解
  8. 鼠标控制视角wasd移动_绝地求生:为什么控制方向键是WASD?网友:就不能是其他键位吗?...
  9. 【C++ Primer】 神秘的 sizeof(union) 、sizeof(struct) 和内存对齐技术
  10. 写一个自己的QQ签名
  11. 利用Code First在MVC4中创建数据驱动应用程序
  12. WinRAR美化增强版 v5.10 简体中文版
  13. yuv422sp to yuv422p
  14. 利用 CSS 实现文字二次加粗和多重边框效果
  15. 城市轨道交通运营管理属于什么院系_城市轨道交通运营管理专业
  16. mp4 html5 自动播放,网页自动播放视频(mp4)
  17. 有监督学习、无监督学习、半监督学习、强化学习
  18. android平板游戏隐藏功能,平板电脑怎么隐藏游戏
  19. 2015年App Store审核被拒的23个理由
  20. 河南的抗疫英雄,给出一系列抗疫英雄的姓名和来自的省份,现在请你帮忙统计来自河南的抗疫英雄有多

热门文章

  1. 如何写一份让面试官眼前一亮的简历?
  2. 微博并发这么牛逼!看他架构如何设计的?
  3. 这位图灵奖得主大佬,你可知道?
  4. try-catch-finally中的4个巨坑,老程序员也搞不定!
  5. 值得推荐的Idea十二大优秀插件
  6. 某网友发表如此言论:程序员基本都是diao丝,是农村进城务工人员!有资源有关系的都不干程序员!...
  7. 百度股价一跌再跌,网友叹息:李彦宏没有狼性,缺乏战略眼光?
  8. 如何提升你的能力?给年轻程序员的几条建议
  9. 如何做产品路线图规划?
  10. VO 1 先弄明白在干什么