Rate this Page

torch.Tensor.new_tensor#

Tensor.new_tensor(data,*,dtype=None,device=None,requires_grad=False,layout=torch.strided,pin_memory=False)Tensor#

Returns a new Tensor withdata as the tensor data.By default, the returned Tensor has the sametorch.dtype andtorch.device as this tensor.

Warning

new_tensor() always copiesdata. If you have a Tensordata and want to avoid a copy, usetorch.Tensor.requires_grad_()ortorch.Tensor.detach().If you have a numpy array and want to avoid a copy, usetorch.from_numpy().

Warning

When data is a tensorx,new_tensor() reads out ‘the data’ from whatever it is passed,and constructs a leaf variable. Thereforetensor.new_tensor(x) is equivalent tox.detach().clone()andtensor.new_tensor(x,requires_grad=True) is equivalent tox.detach().clone().requires_grad_(True).The equivalents usingdetach() andclone() are recommended.

Parameters

data (array_like) – The returned Tensor copiesdata.

Keyword Arguments
  • dtype (torch.dtype, optional) – the desired type of returned tensor.Default: if None, sametorch.dtype as this tensor.

  • device (torch.device, optional) – the desired device of returned tensor.Default: if None, sametorch.device as this tensor.

  • requires_grad (bool,optional) – If autograd should record operations on thereturned tensor. Default:False.

  • layout (torch.layout, optional) – the desired layout of returned Tensor.Default:torch.strided.

  • pin_memory (bool,optional) – If set, returned tensor would be allocated inthe pinned memory. Works only for CPU tensors. Default:False.

Example:

>>>tensor=torch.ones((2,),dtype=torch.int8)>>>data=[[0,1],[2,3]]>>>tensor.new_tensor(data)tensor([[ 0,  1],        [ 2,  3]], dtype=torch.int8)