pytorch(三)——Tensor张量的运算

注:以下均基于导入库

import torch
import torch as t
import torch.nn as nn
import torch.nn.functional as F
  • 构造方法

    常用函数

  • .reshape()#变形

  • .size()#返回大小

  • .dim()#返回维度,即size返回的数据条目个数

  • .numel()#返回元素个数,即size返回条目之积

  • .dtype#查看元素类型,int默认torch.int64,bool默认torch.uint8,float默认touch.float32

  • 常用计算

  • .repeat() 重复

  • 增减维度unsqueeze 、squeeze(不改变元素位置)

a=torch.Tensor([[1,2,3],[4,5,6]])
print(a.size())#torch.Size([2, 3])

b=a.unsqueeze(2)#括号里为维度增加的位置
print(b.size())#torch.Size([2, 3, 1])

c=b.squeeze(-1)#去维度
print(c.size())#torch.Size([2, 3])
  • .sequeeze()可消除张量大小中大小为1的维度

  • .unsqueeze()可增加以下大小为0的维度

  • permute()/transpose()/t()张量的交换、张量的转置、二维张量转置

  • Tensor连接cat

a=torch.Tensor([[1,2,3],[4,5,6]])
d=torch.ones([2,3])
e=torch.cat([a,d],1)
print(e)
print(torch.cat([a **i for i in range(3)],1))
#result:
# tensor([[1., 2., 3., 1., 1., 1.],
#         [4., 5., 6., 1., 1., 1.]])
# tensor([[ 1.,  1.,  1.,  1.,  2.,  3.,  1.,  4.,  9.],
#         [ 1.,  1.,  1.,  4.,  5.,  6., 16., 25., 36.]])
  • 大于某个值ge

a=torch.Tensor([[1,2,3],[4,5,6]])
b=torch.Tensor([0.3,0.40,0.6,0.8,0.1])
print(b.ge(0.5))#tensor([0, 0, 1, 1, 0], dtype=torch.uint8)
print(b.ge(0.5).float())#tensor([0., 0., 1., 1., 0.])
cor=((b.ge(0.5).float()==torch.ones(5)).sum())
print(cor)#tensor(2)
print(b.size(),b.size(0))#torch.Size([5]) 5

加法

数据类型转换

tensor->numpy   .numpy()

numpy->tensor  torch.numpy(X)

import torch
a=torch.eye(2,3)
print(a)
'''
tensor([[1., 0., 0.],
        [0., 1., 0.]])
'''
a.add_(1)
print(a)
'''
tensor([[2., 1., 1.],
        [1., 2., 1.]])
'''
b=a.numpy()
print(type(b))   # <class 'numpy.ndarray'>
c=torch.from_numpy(b)
print(type(c))   # <class 'torch.Tensor'>

 

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值