torch中reshape()和view()

二者功能类似,都是为了改变tensor的shape。

不同点在于view()只是改变shape,数据还是原来的数据;并且view()只能处理连续的内存,因此前面经常跟一个contiguous();

而reshape()则没那么可控,他的执行结果可能是源数据的一个copy,也可能不是。是不是很蛋疼。

文档中这么说:

Returns a tensor with the same data and number of elements as input, but with the specified shape. When possible, the 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.

也就是说Contiguous inputs并且compatible strides才不会返回copying。所以,

if you need a copy use clone() if you need the same storage use view(). The semantics of reshape() are that it may or may not share the storage and you don't know beforehand.

如果需要copy,用clone();如果需要源数据,用view();reshape()这玩意不好控制,最好少用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值