這是一個常用的api 這裏對其儘可能描述
torch.tensor
torch.tensor(data, dtype=None, device=None, requires_grad=False, pin_memory=False) → Tensor
使用數據**data**構造一個tensor
'''
Returns a tensor filled with uninitialized data. The shape of the tensor is defined by the variable argument size.
Parameters
data (array_like) – Initial data for the tensor. Can be a list, tuple, NumPy ndarray, scalar, and other types.
dtype (torch.dtype, optional) – the desired data type of returned tensor. Default: if None, infers data type from data.
device (torch.device, optional) – the desired device of returned tensor. Default: if None, uses the current device for the default tensor type (see torch.set_default_tensor_type()). device will be the CPU for CPU tensor types and the current CUDA device for CUDA tensor types.
requires_grad (bool, optional) – If autograd should record operations on the returned tensor. Default: False.
'''
參數說明
data : 使用該數據初始化tensor,可以是一個list tuple NumPy ;其實這裏也可以是一個tensor
dtype (torch.dtype, optional) – the desired data type of returned tensor. Default: if None, infers data type from data.
dtype:(可選)不設置值 那麼tensor的數據類型就是和data的數據類型是一致的,如果需要設置那就是torch.dtype的那幾個。作用是指定返回tensor的數據類型
device:(可選)就是創建的tensor存放的device,這裏就不做贅述了,大致概念瞭解看這裏\
requires_grad: (可選)是bool 類型的值,默認值是False .因爲 pytorch 後期的版本將Varibale 和Tensor進行合併了,這裏的如果設置爲Flase 表示再反響傳播的時候不會對這個節點機型求導,如果你對tensorflow熟悉,
例子
demo1
y=torch.tensor([[1,2,3]])
print(y) # 這裏的輸出的y的是 tensor([[1, 2, 3]])
其他注意事項
爲了能夠很好的理解下面的這段話,首先這裏講解一下 detach()
detach就是截斷反向傳播的梯度流。
Returns a new Variable, detached from the current graph。將某個node變成不需要梯度的Varibale。因此當反向傳播經過這個node時,梯度就不會從這個node往前面傳播。
torch.tensor()在執行的時候是將data進行copy了一份 如果不想copy可以根據data的類型使用不同的代碼,這裏給出pytorch 官方的提示:
關於detach概念和作用請看這篇博客