pytorch中张量中常用操作

创建size为[2,3]的浮点数张量:
x = torch.FloatTensor(2,3)
输出为tensor([[-5.6497e-27,  8.5619e-43, -5.6497e-27],
        [ 8.5619e-43, -2.0937e-26,  8.5619e-43]])

创建数据为2,3的浮点数张量
x = torch.FloatTensor([2,3])
输出为tensor([2., 3.])

转换为整型张量
x = x.type_as(torch.IntTensor())
输出为tensor([2, 3], dtype=torch.int32)
GPU和CPU上的Tensor转换
>>> x = torch.FloatTensor([[1,2,3],[4,5,6]])
>>> print(x)
tensor([[1., 2., 3.],
        [4., 5., 6.]])

将x移动到GPU上
>>> x_gpu = x.cuda()
>>> print(x_gpu)
tensor([[1., 2., 3.],
        [4., 5., 6.]], device='cuda:0')

将x移动到CPU上
>>> x_cpu = x_gpu.cpu()
>>> print(x_cpu)
tensor([[1., 2., 3.],
        [4., 5., 6.]])

tensor的形状
>>> x = torch.FloatTensor(10,12,3,3)
>>> print(x.size()[:])
torch.Size([10, 12, 3, 3])
torch.index_select(input, dim, index, out=None) → Tensor

函数作用:Returns a new tensor which indexes the input tensor along dimension dim using the entries in index which is a LongTensor.
The returned tensor has the same number of dimensions as the original tensor (input). 
The dimth dimension has the same size as the length of index; other dimensions have the same size as in the original tensor.
The returned tensor does not use the same storage as the original tensor. 
用法:
>>> x = torch.randn(3,4)
>>> x
tensor([[ 0.3221, -1.1750, -0.3818,  1.4253],
        [ 0.9451,  0.8435, -2.3493,  0.0100],
        [-1.7050, -1.1493,  0.5394,  0.7163]])
>>> indices = torch.tensor([0,2])
>>> torch.index_select(x,0,indices)
tensor([[ 0.3221, -1.1750, -0.3818,  1.4253],
        [-1.7050, -1.1493,  0.5394,  0.7163]])
>>> torch.index_select(x, 1, indices)
tensor([[ 0.3221, -0.3818],
        [ 0.9451, -2.3493],
        [-1.7050,  0.5394]])
torch.masked_select(input, mask, out=None) → Tensor

函数作用:Returns a new 1-D tensor which indexes the input tensor according to the boolean mask mask w
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值