0
点赞
收藏
分享

微信扫一扫

pytorch基础知识之Tensor(1)

艾晓雪 2022-04-18 阅读 95

Tensor定义

1.张量 :对于标量,矩阵,向量更加泛化的表述。可以说矩阵就是2阶的张量,张量可以表示数据的任意维度
在这里插入图片描述
在这里插入图片描述
以下是创建一些张量代码实例

import torch
#传数据(FlotTensor类型)
a = torch.Tensor( [ [1,2],[3,4] ] )

#基础构造函数
a = torch.Tensor(2,3)
#几种特殊
b = torch.zeros(3,5)
b = torch.ones(2,2)
b = torch.eye(3,3)

c = torch.zeros_like(a)
c = torch.ones_like(a)

#.........随机
a = torch.rand(2,2)
#........正态
a = torch.normal(mean = 0.0, std = torch.rand(2,3)) #mean为均值, std为标准差
a = torch.normal(mean = torch.rand(2,5),std = torch.rand(2,5) )
#..............均匀分布 (FlotTensor类型)
a = torch.Tensor(1,3).uniform_(0,1)
#........序列  (LongTensor类型)
a = torch.arange(0,10,2)  #步长为2,最后结尾值不包含在序列中
a  = torch.linspace(1,10, 3) #拿到等间隔的3个数字,结尾值包含10
#........随机排列(LongTensor类型)
a = torch.randperm(15)   #0-14,数字随机排列
print(a)
print(a.type())



Tensor的三个属性

每个Tensor都有torch.dtype, torch.device, torch.layout三种属性。
torch.dtype :数据类型
torch.device :标识创建Tensor对象之后所存储的设备名称,有CPU/GPU(cuda)
torch.layout :表示内存布局对象,有稠密和稀疏之分。上面代码块都是稠密的方式。非零个数越少,数据越稀疏。
稀疏张量只会记录非零元素的坐标和值,这样会节省资源
torch.sparse_coo_tensor():稀疏张量定义
以下是关于Tensor属性的代码实例

import torch
dev = torch.device("cpu")
#dev = torch.device("cuda")
a = torch.tensor([2,2], dtype = torch.float32, device=dev)


#定义稀疏张量
i = torch.tensor([ [0,1,2], [0,1,2] ]) #非零元素坐标
v = torch.tensor([1,2,3])  #元素值
a = torch.sparse_coo_tensor(i, v, (4,4), dtype=torch.float32, device=dev)
b = a.to_dense() #转成稠密张量

print(b)

在这里插入图片描述

Tensor的运算

加法:c = a +b
c = torch.add(a, b)
a.add(b)
a.add_(b) [注,最后一种和上面三种机制不一样,它不仅把结果计算出来还会修改a的值,把结果赋予a。运算函数中带下划线的都类似]

   减法:c = a-b      c = torch.sub(a,b)     a.sub(b)      a.sub_(b)

乘法,哈达玛积(矩阵对应元素相乘):

c = a*b     c = torch.mul(a,b)    a.mul(b)    a.mul_(b)

除法:

c = a / b       c = torch.div(a, b)        a.div(b)       a.div_(b)

二维矩阵乘法运算有 torch.mm() 、 torch.matmul() 、 @,以下有四种方式实现

a = torch.ones(2,3)    b = torch.ones(3,2)
print( torch.mm(a,b) )  
print( torch.matmul(a,b) )
print( a@b )
print( a.mm(b) )
print( a.matmul(b) )

对于高维的Tensor(dim>2),定义矩阵乘法仅在最后的两个维度上,前面的维度必须保持一致,如下a, b 所定义那样,且运算操作只有torch.matmul()

a = torch.ones(1, 2, 3, 4)   
b = torch.ones(1, 2, 4, 3)
print(  a.matmul(b) )
print(  torch.matmul(a, b) )

幂运算:
print( torch.pow(a, 2) ) print( a.pow(2) ) print( a**2 )
print( a.pow_(2) ) #注意这里会修改a的值
e^n 有如下表示

   print( torch.exp(n) )        b = n.exp_()[这里会把结果给n]

开方运算

print(  a.sqrt() )                      print( a.sqrt_() )

对数运算

print( torch.log2(a) )
print( torch.log10(a) )
print( torch.log(a) )    print( torch.log_(a) )  [以e为底]

取整取余运算

print( torch.floor(a) ) # 向下取整数
print( torch.ceil(a) )  # 向上取整数
print( torch.round(a) ) # 四舍五入 >=0.5向上取, <0.5向下取
print( torch.trunc(a) ) # 剪裁,只取整数部分
print( torch.frac(a) )  #  只取小数部分
print(a % 2)            #   取余

Tensor的比较运算,

(1-6机制一样,都是返回一个Tensor,里面有Ture or  False)
1. torch.eq( input, other, out=None ) #按成员进行等式操作,相同返回Ture
2. torch.ge( input, other, out=None )  #input >= other
3. torch.gt( input, other, out=None )  #input > other
4. torch.le( input, other, out=None )  #input =< other
5. torch.lt( input, other, out=None )  #input < other
6. torch.ne( input, other, out=None )  #input != other

7. torch.equal( Tensor1, Tensor2 ) #若两者有相同的size 和 elements,则为Ture

Tensor的排序及索引
torch.sort( input, dim=None, descending = False, out = None ) #对目标input进行排序

a = torch.tensor( [1, 4, 4, 3, 5] )
print( torch.sort(a) )
**运行结果如下:**
torch.return_types.sort(
values=tensor([1, 3, 4, 4, 5]),   结果
indices=tensor([0, 3, 1, 2, 4])), 对应数值的索引值


a = torch.tensor(  [[1, 4, 4, 3, 5],
                    [3, 4, 2, 1, 8]] )
print( torch.sort(a, dim=0, descending= True) ) # 2这个维度进行降序排列
**运行结果如下:**
values=tensor([[3, 4, 4, 3, 8],
        [1, 4, 2, 1, 5]]),
indices=tensor([[1, 0, 0, 0, 1],
        [0, 1, 1, 1, 0]]))

Tensor取前K大/小值及其索引
torch.topk( input, k, dim = None, largest = True, sorted = True, out = None )#沿着指定维度返回最大/最小K个数值及其索引值

a = torch.tensor(  [[1, 4, 2, 3, 5],
                    [9, 5, 3, 1, 8]] )
print(torch.topk( a, k=2, dim=1 )) #沿着5这个维度取2个最大值并排序
**运行结果如下**
torch.return_types.topk(
values=tensor([[5, 4],
        [9, 8]]),
indices=tensor([[4, 1],
        [0, 4]]))


a = torch.tensor(  [[1, 4, 2, 3, 5],
                    [9, 5, 3, 1, 8]] )
print(torch.topk( a, k=1, dim=0, largest=False ))  #沿着2这个维度取一个最小值
**运行结果如下**
torch.return_types.topk(
values=tensor([[1, 4, 2, 1, 5]]),
indices=tensor([[0, 0, 0, 1, 0]]))

torch.kthvalue( input, k, dim=None, out = None ) #沿着指定维度返回第K个最小值及其索引值

a = torch.tensor(  [[1, 4, 2, 3, 5],
                    [9, 5, 3, 1, 8]] )
print( torch.kthvalue(a, k = 2, dim=1) )  #沿着5这个维度取第2个最小值
**运行结果如下:**
torch.return_types.kthvalue(
values=tensor([2, 3]),  #第一行第二个最小值为2,第二行第二个最小值为3
indices=tensor([2, 2]))

判定当前Tensor的每个元素是否是 有界,无界,返回一个带true or false 的tensor
torch.isfinite( tensor ) #有界
torch.isinf( tensor ) #无界
torch.isnan( tensor ) #空

举报

相关推荐

0 条评论