CLASS torch.Tensor
There are a few main ways to create a tensor, depending on your use case.
-
To create a tensor with pre-existing data, use torch.tensor().
-
To create a tensor with specific size, use torch.* tensor creation ops (see Creation Ops).
-
To create a tensor with the same size (and similar types) as another tensor, use torch.*_like tensor creation ops (see Creation Ops).
-
To create a tensor with similar type but different size as another tensor, use tensor.new_* Creation ops.
import torch
1. tensor.new_*
x = torch.tensor((), dtype=torch.float64)
x
tensor([], dtype=torch.float64)
# tensor.new_zeros返回与x具有相同数据类型torch.dtype和设备类型torch.device的张量
x_new = x.new_zeros((2,3))
x_new
tensor([[0., 0., 0.],
[0., 0., 0.]], dtype=torch.float64)
2. torch.*_like
# torch.zeros_like
# Returns a tensor filled with the scalar value 0, with the same size as input.
# torch.zeros_like(input) is equivalent to torch.zeros(input.size(), dtype=input.dtype, layout=input.layout, device=input.device).
y = torch.zeros_like(x_new)
y
tensor([[0., 0., 0.],
[0., 0., 0.]], dtype=torch.float64)