torch.Tensor¶
A torch.Tensor
is a multi-dimensional matrix containing elements of
a single data type.
Torch defines seven CPU tensor types and eight GPU tensor types:
Data type | CPU tensor | GPU tensor |
---|---|---|
32-bit floating point | torch.FloatTensor |
torch.cuda.FloatTensor |
64-bit floating point | torch.DoubleTensor |
torch.cuda.DoubleTensor |
16-bit floating point | torch.HalfTensor |
torch.cuda.HalfTensor |
8-bit integer (unsigned) | torch.ByteTensor |
torch.cuda.ByteTensor |
8-bit integer (signed) | torch.CharTensor |
torch.cuda.CharTensor |
16-bit integer (signed) | torch.ShortTensor |
torch.cuda.ShortTensor |
32-bit integer (signed) | torch.IntTensor |
torch.cuda.IntTensor |
64-bit integer (signed) | torch.LongTensor |
torch.cuda.LongTensor |
The torch.Tensor
constructor is an alias for the default tensor type
(torch.FloatTensor
).
A tensor can be constructed from a Python list
or sequence:
>>> torch.FloatTensor([[1, 2, 3], [4, 5, 6]])
1 2 3
4 5 6
[torch.FloatTensor of size 2x3]
An empty tensor can be constructed by specifying its size:
>>> torch.IntTensor(2, 4).zero_()
0 0 0 0
0 0 0 0
[torch.IntTensor of size 2x4]
The contents of a tensor can be accessed and modified using Python’s indexing and slicing notation:
>>> x = torch.FloatTensor([[1, 2, 3], [4, 5, 6]])
>>> print(x[1][2])
6.0
>>> x[0][1] = 8
>>> print(x)
1 8 3
4 5 6
[torch.FloatTensor of size 2x3]
Each tensor has an associated torch.Storage
, which holds its data.
The tensor class provides multi-dimensional, strided
view of a storage and defines numeric operations on it.
Note
Methods which mutate a tensor are marked with an underscore suffix.
For example, torch.FloatTensor.abs_()
computes the absolute value
in-place and returns the modified tensor, while torch.FloatTensor.abs()
computes the result in a new tensor.
-
class
torch.
Tensor
¶ -
class
torch.
Tensor
(*sizes) -
class
torch.
Tensor
(size) -
class
torch.
Tensor
(sequence) -
class
torch.
Tensor
(ndarray) -
class
torch.
Tensor
(tensor) -
class
torch.
Tensor
(storage) Creates a new tensor from an optional size or data.
If no arguments are given, an empty zero-dimensional tensor is returned. If a
numpy.ndarray
,torch.Tensor
, ortorch.Storage
is given, a new tensor that shares the same data is returned. If a Python sequence is given, a new tensor is created from a copy of the sequence.
-
class
torch.
ByteTensor
¶ The following methods are unique to
torch.ByteTensor
.