前言
使用pytorch框架,会常操作tensor,以下则是对tensor常规操作的汇总。
import torch
torch.Tensor
会继承某些torch
的某些数学运算,例如sort, min/max....不需要调用相应的torch.funciton
进行处理,下文中如果是torch/Tensor
即表示该函数可以直接对self的tensor使用,也可以使用torch给的相应函数接口
1.torch/Tensor.reshape(input, shape) → Tensor
指定tensor新的shape,reshape过后不会更该数据量和数据格式,只是对数据的shape做了调整,因此要保证reshape前后元素个数一致。 参数:
input(tensor) - 输入tensor
shape(tuple or *size) - 新的shape 如果还剩下一个维度,很好,你可以直接使用-1来替代,表示这个维度中应该有的元素数量
2.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.
二者区别: