torch.Tensor
Tensor
A torch.Tensor is a multi-dimensional matrix containing numbers.
Initializing Tensors
A tensor can be constructed from a Python list or sequence using the torch.tensor() constructor:
>>> torch.tensor([[1., -1.], [1., -1.]])
tensor([[1, -1], [1, -1]])
>>> torch.tensor([1, 2, 3, 4])
tensor([1, 2, 3, 4])You can also use tensor creation ops:
>>> torch.zeros(2, 3)
tensor([[0, 0, 0], [0, 0, 0]])
>>> torch.ones(2, 3)
tensor([[1, 1, 1], [1, 1, 1]])
>>> torch.randn(2, 3)
tensor([[0.04188625638329904, -0.2835499126703179, 0.15911637825403122], [-0.35108857534104865, 1.606089739430864, 0.013343448166239665]])Tensor Attributes
| Attribute | Description |
|---|---|
shape | Returns the shape of the tensor. |
data | Returns a detached view of the tensor data (no gradient). |
requires_grad | Is True if gradients need to be computed for this Tensor. |
grad | This attribute is None by default and becomes a Tensor the first time a call to backward() computes gradients for self. |
T | Returns a view of this tensor with its dimensions reversed. |
Tensor Methods
The contents of a tensor can be accessed using Python’s indexing and slicing notation:
>>> x = torch.tensor([[1, 2, 3], [4, 5, 6]])
>>> x[0]
tensor([1, 2, 3])
>>> x[1, 2]
tensor(6)
>>> x[0:2]
tensor([[1, 2, 3], [4, 5, 6]])Integer indexing selects along dimension 0 and returns a tensor with one fewer dimension. Tuple indexing chains dimension-0 selections (e.g. x[i, j] is equivalent to x[i][j]). Slice indexing returns a new tensor containing the selected rows.
Use torch.Tensor.item() to get a Python number from a tensor containing a single value:
>>> x = torch.tensor([[1]])
>>> x
tensor([[1]])
>>> x.item()
1
>>> x = torch.tensor(2.5)
>>> x
tensor(2.5)
>>> x.item()
2.5| Method | Description |
|---|---|
tolist() | Return tensor data as a (nested) Python list, or a Python scalar for 0-d tensors. |
item() | Returns the value of this tensor as a standard Python number. |
size(dim=None) | Returns the size of the self tensor. |
dim() | Returns the number of dimensions of self tensor. |
numel() | Returns the total number of elements in the self tensor. |
backward(gradient=None) | Computes the gradient of current tensor w.r.t. graph leaves. |
detach() | Returns a new Tensor, detached from the current graph. |
zero_() | Fills self tensor with zeros. |
retain_grad() | Enables .grad attribute for non-leaf Tensors. |
reshape(*args) | Returns a tensor with the same data and number of elements as self but with the specified shape. |
view(*args) | Returns a new tensor with the same data as the self tensor but of a different shape. |
squeeze(dim=None) | Returns a tensor with all specified dimensions of input of size 1 removed. |
unsqueeze(dim) | Returns a new tensor with a dimension of size one inserted at the specified position. |
expand(*args) | Returns a new view of the self tensor with singleton dimensions expanded to a larger size. |
transpose(dim0, dim1) | Returns a tensor that is a transposed version of self. |
flatten(start_dim=0, end_dim=-1) | Flattens self tensor by reshaping it into a one-dimensional tensor. |
Reductions
| Method | Description |
|---|---|
sum(dim=None, keepdim=False) | Returns the sum of all elements in the tensor. |
mean(dim=None, keepdim=False) | Returns the mean value of all elements in the tensor. |
max(dim=None, keepdim=False) | Returns the maximum value of all elements in the tensor. |
min(dim=None, keepdim=False) | Returns the minimum value of all elements in the tensor. |
Math Operations
Many math operations are exposed directly as tensor methods: add(other), sub(other), mul(other), div(other), pow(other), matmul(other), neg(), abs(), log(), exp(), sqrt(), square(), sin(), cos(), tan(), sigmoid(), relu(), sign(), reciprocal(), nan_to_num().
Additionally, the Python __add__, __sub__, __mul__, __truediv__, __pow__, and __matmul__ magic methods are implemented to match standard math operators (+, -, *, /, **, @).
Comparison Operations
| Method | Description |
|---|---|
lt(other) | Computes self < other element-wise. |
gt(other) | Computes self > other element-wise. |
le(other) | Computes self <= other element-wise. |
ge(other) | Computes self >= other element-wise. |
eq(other) | Computes self == other element-wise. |
ne(other) | Computes self != other element-wise. |
allclose(other, rtol=1e-5, atol=1e-8, equal_nan=False) | This function checks if self and other satisfy the condition. |
Method and Attribute Details
torch.Tensor.shape PyTorch↗
Returns the shape of the tensor as a tuple.
>>> x = torch.tensor([[1, 2], [3, 4]])
>>> x.shape
(2, 2)torch.Tensor.data
Returns a detached view of the tensor data (no gradient).
>>> x = torch.tensor([1., 2.], requires_grad=True)
>>> x.data
tensor([1, 2])
>>> x.data.requires_grad
Falsetorch.Tensor.requires_grad PyTorch↗
Is True if gradients need to be computed for this Tensor, False otherwise.
>>> x = torch.tensor([1., 2.], requires_grad=True)
>>> x.requires_grad
Truetorch.Tensor.grad PyTorch↗
This attribute is None by default and becomes a Tensor the first time a call to backward() computes gradients for self.
>>> x = torch.tensor([1., 2.], requires_grad=True)
>>> y = x.sum()
>>> y.backward()
>>> x.grad
tensor([1, 1])torch.Tensor.T
Returns a view of this tensor with its dimensions reversed.
>>> x = torch.tensor([[1, 2], [3, 4]])
>>> x.T
tensor([[1, 3], [2, 4]])WARNING
The use of Tensor.T on tensors of dimension other than 2 to reverse their shape is deprecated and it will throw an error.
torch.Tensor.tolist PyTorch↗
Tensor.tolist() -> listReturn tensor data as a (nested) Python list, or a Python scalar for 0-d tensors.
>>> x = torch.tensor([[1, 2], [3, 4]])
>>> x.tolist()
[[1, 2], [3, 4]]torch.Tensor.item PyTorch↗
Tensor.item() -> numberReturns the value of this tensor as a standard Python number. This only works for tensors with one element.
>>> x = torch.tensor([3])
>>> x.item()
3torch.Tensor.size PyTorch↗
Tensor.size(dim=None) -> tuple or intReturns the size of the self tensor. If dim is not specified, returns the full shape tuple.
>>> x = torch.tensor([[1, 2], [3, 4]])
>>> x.size()
(2, 2)
>>> x.size(1)
2torch.Tensor.dim PyTorch↗
Tensor.dim() -> intReturns the number of dimensions of self tensor.
>>> x = torch.tensor([[1, 2], [3, 4]])
>>> x.dim()
2torch.Tensor.numel PyTorch↗
Tensor.numel() -> intReturns the total number of elements in the self tensor.
>>> x = torch.tensor([[1, 2], [3, 4]])
>>> x.numel()
4torch.Tensor.backward PyTorch↗
Tensor.backward(gradient=None)Computes the gradient of current tensor w.r.t. graph leaves.
>>> x = torch.tensor([1., 2.], requires_grad=True)
>>> y = x.sum()
>>> y.backward()
>>> x.grad
tensor([1, 1])torch.Tensor.detach PyTorch↗
Tensor.detach() -> TensorReturns a new Tensor, detached from the current graph.
>>> x = torch.tensor([1., 2.], requires_grad=True)
>>> y = x.detach()
>>> y.requires_grad
Falsetorch.Tensor.zero_ PyTorch↗
Tensor.zero_() -> TensorFills self tensor with zeros.
>>> x = torch.tensor([1., 2.])
>>> x.zero_()
tensor([0, 0])
>>> x
tensor([0, 0])torch.Tensor.retain_grad PyTorch↗
Tensor.retain_grad()Enables .grad attribute for non-leaf Tensors.
>>> x = torch.tensor([1., 2.], requires_grad=True)
>>> y = x * 2
>>> y.retain_grad()
>>> z = y.sum()
>>> z.backward()
>>> y.grad
tensor([1, 1])torch.Tensor.reshape PyTorch↗
Tensor.reshape(*args) -> TensorSee torch.reshape.
torch.Tensor.view PyTorch↗
Tensor.view(*args) -> TensorReturns a new tensor with the same data as the self tensor but of a different shape.
>>> x = torch.tensor([1, 2, 3, 4])
>>> x.view(2, 2)
tensor([[1, 2], [3, 4]])torch.Tensor.squeeze PyTorch↗
Tensor.squeeze(dim=None) -> TensorSee torch.squeeze.
torch.Tensor.unsqueeze PyTorch↗
Tensor.unsqueeze(dim) -> TensorSee torch.unsqueeze.
torch.Tensor.expand PyTorch↗
Tensor.expand(*args) -> TensorReturns a new view of the self tensor with singleton dimensions expanded to a larger size.
>>> x = torch.tensor([1])
>>> x.expand(3)
tensor([1, 1, 1])torch.Tensor.transpose PyTorch↗
Tensor.transpose(dim0, dim1) -> TensorSee torch.transpose.
torch.Tensor.flatten PyTorch↗
Tensor.flatten(start_dim=0, end_dim=-1) -> TensorSee torch.flatten.
torch.Tensor.sum PyTorch↗
Tensor.sum(dim=None, keepdim=False) -> TensorSee torch.sum.
torch.Tensor.mean PyTorch↗
Tensor.mean(dim=None, keepdim=False) -> TensorSee torch.mean.
torch.Tensor.max PyTorch↗
Tensor.max(dim=None, keepdim=False) -> TensorSee torch.max.
torch.Tensor.min PyTorch↗
Tensor.min(dim=None, keepdim=False) -> TensorSee torch.min.
torch.Tensor.add PyTorch↗
Tensor.add(other) -> TensorSee torch.add.
torch.Tensor.sub PyTorch↗
Tensor.sub(other) -> TensorSee torch.sub.
torch.Tensor.mul PyTorch↗
Tensor.mul(other) -> TensorSee torch.mul.
torch.Tensor.div PyTorch↗
Tensor.div(other) -> TensorSee torch.div.
torch.Tensor.pow PyTorch↗
Tensor.pow(other) -> TensorSee torch.pow.
torch.Tensor.matmul PyTorch↗
Tensor.matmul(other) -> TensorSee torch.matmul.
torch.Tensor.neg PyTorch↗
Tensor.neg() -> TensorSee torch.neg.
torch.Tensor.abs PyTorch↗
Tensor.abs() -> TensorSee torch.abs.
torch.Tensor.log PyTorch↗
Tensor.log() -> TensorSee torch.log.
torch.Tensor.exp PyTorch↗
Tensor.exp() -> TensorSee torch.exp.
torch.Tensor.sqrt PyTorch↗
Tensor.sqrt() -> TensorSee torch.sqrt.
torch.Tensor.square PyTorch↗
Tensor.square() -> TensorSee torch.square.
torch.Tensor.sin PyTorch↗
Tensor.sin() -> TensorSee torch.sin.
torch.Tensor.cos PyTorch↗
Tensor.cos() -> TensorSee torch.cos.
torch.Tensor.tan PyTorch↗
Tensor.tan() -> TensorSee torch.tan.
torch.Tensor.sigmoid PyTorch↗
Tensor.sigmoid() -> TensorSee torch.sigmoid.
torch.Tensor.relu
Tensor.relu() -> TensorSee torch.relu.
torch.Tensor.sign PyTorch↗
Tensor.sign() -> TensorSee torch.sign.
torch.Tensor.reciprocal PyTorch↗
Tensor.reciprocal() -> TensorSee torch.reciprocal.
torch.Tensor.nan_to_num PyTorch↗
Tensor.nan_to_num() -> TensorSee torch.nan_to_num.
torch.Tensor.lt PyTorch↗
Tensor.lt(other) -> TensorSee torch.lt.
torch.Tensor.gt PyTorch↗
Tensor.gt(other) -> TensorSee torch.gt.
torch.Tensor.le PyTorch↗
Tensor.le(other) -> TensorSee torch.le.
torch.Tensor.ge PyTorch↗
Tensor.ge(other) -> TensorSee torch.ge.
torch.Tensor.eq PyTorch↗
Tensor.eq(other) -> TensorSee torch.eq.
torch.Tensor.ne PyTorch↗
Tensor.ne(other) -> TensorSee torch.ne.
torch.Tensor.allclose PyTorch↗
Tensor.allclose(other, rtol=1e-5, atol=1e-8, equal_nan=False) -> boolSee torch.allclose.