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()這玩意不好控制,最好少用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章