pytorch中深度拷贝_Pytorch深度指南-torch与Tensor常用操作方法

pytorch深度指南-torch与Tensor常用操作方法

import torch

torch.Tensor会继承某些torch的某些数学运算,例如sort, min/max....不需要调用相应的torch.funciton进行处理,下文中如果是torch/Tensor即表示该函数可以直接对self的tensor使用,也可以使用torch给的相应函数接口

torch/Tensor.reshape(input, shape) → Tensor

指定tensor新的shape,reshape过后不会更该数据量和数据格式,只是对数据的shape做了调整,因此要保证reshape前后元素个数一致。 参数:

input(tensor) - 输入tensor

shape(tuple or *size) - 新的shape 如果还剩下一个维度,很好,你可以直接使用-1来替代,表示这个维度中应该有的元素数量

torch/Tensor.view()

与reshape功能类似,将源tensor的shape改变指定形状。

原文中这样描述 Returned tensor will be a view of input. Otherwise, it will be a copy. Contiguous inputs and inputs with compatible strides can be reshaped without copying, but you should not depend on the copying vs. viewing behavior.二者区别:当tensor都为contiguous类型(邻近模式)时,两个函数并无差异,使用原来的数据内容,不会复制一份新的出来;如果tensor不是,例如经过了transpose或permute之后,需要contiguous然后再使用view。reshape其实就是.contiguous+view,这样不会开辟新的空间存放tensor,而是共享原来的数据内存。

torch.arange(10).reshape((2,5))

tensor([[ 0., 1., 2., 3., 4.],

[ 5., 6., 7., 8., 9.]])

torch.arange(10).reshape(5, -1)#可以看到新的shape是(5,2),使用-1自动求剩余最后一个维度

tensor([[ 0., 1.],

[ 2., 3.],

[ 4., 5.],

[ 6., 7.],

[ 8., 9.]])

torch.index_select(input, dim, index, out=None)

指定在哪个轴上,index是多少,注意index要是一个tensor, dim和index确定了一个维度的坐标$(dim_1=index_i,....dim_n=index)$

a = torch.randn([3,4])

print(a)

a.index_select(0,torch.tensor([2])).reshape(2,2)#

tensor([[ 0.0334, 0.9123, -1.2300, -0.9336],

[-0.8364, 0.6584, 0.6878, -2.5896],

[ 0.1862, -0.3752, 0.4150, -1.4008]])

tensor([[ 0.1862, -0.3752],

[ 0.4150, -1.4008]])

torch.linespace(start, end, steps=100, out=None)

返回一个一维tensor,包含step个元素,每个元素之间等间距,依次递增$\frac{end-start}{step}$

torch.linspace(0,1,10, dtype=torch.float32)

tensor([ 0.0000, 0.1111, 0.2222, 0.3333, 0.4444, 0.5556, 0.6667,

0.7778, 0.8889, 1.0000])

Tensor.repeat(input, *size)

把输入的input当做一个基本模块m,扩张成size的tensor,其中每个元素为m,最后返回的Tensor的shape为() *size必须比input的维度要高,

if input和size维度相等:

input = (a,b)

*size 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值