python里面的tensor跟tensorflow里面的tensor都表示张量,包含一些基本的运算。实际上跟numpy数组、向量、矩阵的格式基本一样。但是是专门针对GPU来设计的,可以运行在GPU上来加快计算效率。
PyTorch中定义tensor,就跟numpy定义矩阵、向量差不多,例如定义一个5×3的tensor,每一项都是0的张量:

可以从python的数组直接创建tensor:

也可以直接从pytorch创建:

如果想看某个Tensor的形状的话,使用以下两种方法:(两种方法一样,前者更常见)

常用初始化:





Tensor基本操作:
1.tensor的切片、合并、变形、抽取操作
torch.cat(seq,dim=0,out=None) 把一堆tensor丢进去,按照dim指定的维度拼接、堆叠在一起


torch.chunk(tensor,chunks,dim=0)把tensor切成块,数量由chunks指定

改变形状:torch.reshape(input,shape),把tensor作为函数的输入;
tensor.view(shape),任何tensor的函数都可以。二者的返回值,都只是让我们从另一个视角看某个tensor,所以不会改变本来的形状,除非你把结果又赋值给原来的tensor。



2.基本数学操作
加法:x+y;
torch.add(x,y) 实际上.add()可以接受三个参数:torch.add(input,value,out=None),一般,如果直接torch.add(x,y),那么x,y本身都不会变化的,但是如果设置out=x,那么x久变成加和后的值。

特别地,若想进行in-place操作,就比方说y加上x,y的值就改变了。就可以用y.add_(x),这样y就直接被改变了(类似用法还有x.copy_(y))

乘法:torch.mul(input,other,out=None) 用input乘以othor

除法:torch.div(input,other,out=None) 用input除以other

指数:torch.pow(input,exponent,out=None) input的exponent次方,input为底数,exponent为指数

开根号:torch.sqrt(input,out=None)

(注意 .sqrt()操作是针对浮点型数的)
四舍五入到整数:torch.round(input,out=None)

argmax函数:torch.argmax(input,dim=None,keepdim=False) 返回指定维度最大值的序号,dim给的定义是:the demention to reduce.也就是把dim这个维度的,变成这个维度的最大值的index

取绝对值:torch.abs(input,out=None)
向上取整:torch.ceil(input,out=None)
刀削函数:torch.clamp(input,min,max,out=None) 把输入数据规范在min-max区间内,超过范围的用min、max代替
3、Torch Tensor与Numpy的互相转换
Tensor~Numpy:
直接用.numpy()即可。但是注意,转换后,numpy的变量和原来的tensor会共用底层内存地址,所以如果原来的tensor改变了,numpy变量也会随之改变.

Numpy~Tensor:
用torch.from_numpy()来转换.

by PengSW_10 on 2019/2/8
网友评论