torch张量

原文: https://pytorch.org/docs/stable/tensors.html

torch.Tensor 是包含单个数据类型元素的多维矩阵。

Torch 定义了 9 种 CPU 张量类型和 9 种 GPU 张量类型:

数据类型 dtype CPU 张量 GPU 张量
32 位浮点 torch.float32torch.float torch.FloatTensor torch.cuda.FloatTensor
64 位浮点 torch.float64torch.double torch.DoubleTensor torch.cuda.DoubleTensor
16 位浮点 torch.float16torch.half torch.HalfTensor torch.cuda.HalfTensor
8 位整数(无符号) torch.uint8 torch.ByteTensor torch.cuda.ByteTensor
8 位整数(有符号) torch.int8 torch.CharTensor torch.cuda.CharTensor
16 位整数(有符号) torch.int16torch.short torch.ShortTensor torch.cuda.ShortTensor
32 位整数(有符号) torch.int32torch.int torch.IntTensor torch.cuda.IntTensor
64 位整数(有符号) torch.int64torch.long torch.LongTensor torch.cuda.LongTensor
布尔型 torch.bool torch.BoolTensor torch.cuda.BoolTensor

torch.Tensor 是默认张量类型(torch.FloatTensor)的别名。

可以使用 torch.tensor() 构造函数从 Python list或序列构造张量:

  1. >>> torch.tensor([[1., -1.], [1., -1.]])
  2. tensor([[ 1.0000, -1.0000],
  3. [ 1.0000, -1.0000]])
  4. >>> torch.tensor(np.array([[1, 2, 3], [4, 5, 6]]))
  5. tensor([[ 1, 2, 3],
  6. [ 4, 5, 6]])

警告

torch.tensor() 始终复制data。 如果您具有张量data,而只想更改其requires_grad标志,请使用 requires_grad_()detach() 以避免复制。 如果您有一个 numpy 数组并且想要避免复制,请使用 torch.as_tensor()

可以通过将 torch.dtype 和/或 torch.device 传递给构造函数或张量创建操作来构造特定数据类型的张量:

  1. >>> torch.zeros([2, 4], dtype=torch.int32)
  2. tensor([[ 0, 0, 0, 0],
  3. [ 0, 0, 0, 0]], dtype=torch.int32)
  4. >>> cuda0 = torch.device('cuda:0')
  5. >>> torch.ones([2, 4], dtype=torch.float64, device=cuda0)
  6. tensor([[ 1.0000, 1.0000, 1.0000, 1.0000],
  7. [ 1.0000, 1.0000, 1.0000, 1.0000]], dtype=torch.float64, device='cuda:0')

张量的内容可以使用 Python 的索引和切片符号来访问和修改:

  1. >>> x = torch.tensor([[1, 2, 3], [4, 5, 6]])
  2. >>> print(x[1][2])
  3. tensor(6)
  4. >>> x[0][1] = 8
  5. >>> print(x)
  6. tensor([[ 1, 8, 3],
  7. [ 4, 5, 6]])

使用 torch.Tensor.item() 从张量中获取包含单个值的 Python 数字:

  1. >>> x = torch.tensor([[1]])
  2. >>> x
  3. tensor([[ 1]])
  4. >>> x.item()
  5. 1
  6. >>> x = torch.tensor(2.5)
  7. >>> x
  8. tensor(2.5000)
  9. >>> x.item()
  10. 2.5

可以使用requires_grad=True创建一个张量,以便 torch.autograd 对其进行记录操作以进行自动微分。

  1. >>> x = torch.tensor([[1., -1.], [1., 1.]], requires_grad=True)
  2. >>> out = x.pow(2).sum()
  3. >>> out.backward()
  4. >>> x.grad
  5. tensor([[ 2.0000, -2.0000],
  6. [ 2.0000, 2.0000]])

每个张量都有一个关联的torch.Storage,它保存其数据。 张量类提供了存储的多维跨度视图,并定义了数字运算。

注意

有关 torch.Tensortorch.dtypetorch.devicetorch.layout 属性的更多信息,请参阅[ Tensor Attributes

注意

改变张量的方法用下划线后缀标记。 例如,torch.FloatTensor.abs_()在原位计算绝对值并返回修改后的张量,而torch.FloatTensor.abs()在新张量中计算结果。

注意

要更改现有张量的 torch.device 和/或 torch.dtype ,请考虑在张量上使用 to() 方法。

警告

torch.Tensor 的当前实现引入了内存开销,因此,在具有许多微小张量的应用程序中,它可能导致意外的高内存使用率。 如果是这种情况,请考虑使用一种大型结构。


  1. class torch.Tensor

根据您的用例,创建张量的主要方法有几种。

  • 要使用现有数据创建张量,请使用 torch.tensor()

  • 要创建具有特定大小的张量,请使用torch.*张量创建操作(请参见 Creation Ops)。

  • 要创建与另一个张量具有相同大小(和相似类型)的张量,请使用torch.*_like张量创建操作(请参见创建操作)。

  • 要创建与其他张量具有相似类型但大小不同的张量,请使用tensor.new_*创建操作。


  1. new_tensor(data, dtype=None, device=None, requires_grad=False) Tensor

返回以data作为张量数据的新张量。 默认情况下,返回的张量与此张量具有相同的 torch.dtypetorch.device

警告

new_tensor() 始终复制data。 如果您有张量data并希望避免复制,请使用 torch.Tensor.requires_grad_()torch.Tensor.detach() 。 如果您有一个 numpy 数组并且想要避免复制,请使用 torch.from_numpy()

警告

当数据是张量 x 时, new_tensor() 从传递的任何数据中读出“数据”,并构造一个叶子变量。 因此,tensor.new_tensor(x)等同于x.clone().detach()tensor.new_tensor(x, requires_grad=True)等同于x.clone().detach().requires_grad_(True)。 建议使用clone()detach()的等效项。

参数

  • data (array_like )–返回的张量副本data

  • dtype (torch.dtype ,可选)– 返回张量的所需类型。 默认值:如果为 None,则与此张量相同的 torch.dtype

  • device (torch.device ,可选)– 返回张量的所需设备。 默认值:如果为 None,则与此张量相同的 torch.device

  • require_grad (bool 可选)– 返回的张量是否需要自动求导。 默认值:False

例:

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

  1. new_full(size, fill_value, dtype=None, device=None, requires_grad=False) Tensor

返回大小为 size 的张量,并用fill_value填充。 默认情况下,返回的张量与此张量具有相同的 torch.dtypetorch.device

参数

  • fill_value (标量)–用来填充输出张量的数字。

  • dtype (torch.dtype, optional) – 返回张量的所需类型。 默认值:如果为 None,则与此张量相同的 torch.dtype

  • device (torch.device, optional) – 返回张量的所需设备。 默认值:如果为 None,则与此张量相同的 torch.device

  • requires_grad (bool__, optional) – 返回的张量是否需要自动求导。 默认值:False

例:

  1. >>> tensor = torch.ones((2,), dtype=torch.float64)
  2. >>> tensor.new_full((3, 4), 3.141592)
  3. tensor([[ 3.1416, 3.1416, 3.1416, 3.1416],
  4. [ 3.1416, 3.1416, 3.1416, 3.1416],
  5. [ 3.1416, 3.1416, 3.1416, 3.1416]], dtype=torch.float64)

  1. new_empty(size, dtype=None, device=None, requires_grad=False) Tensor

返回大小为 size 的张量,其中填充了未初始化的数据。 默认情况下,返回的张量具有与此张量相同的 torch.dtypetorch.device

参数

  • dtype (torch.dtype, optional) –

  • device (torch.device, optional) – 返回张量的所需设备。 默认值:如果为 None,则与此张量相同的 torch.device

  • requires_grad (bool__, optional) – 返回的张量是否需要自动求导。 默认值:False

例:

  1. >>> tensor = torch.ones(())
  2. >>> tensor.new_empty((2, 3))
  3. tensor([[ 5.8182e-18, 4.5765e-41, -1.0545e+30],
  4. [ 3.0949e-41, 4.4842e-44, 0.0000e+00]])

  1. new_ones(size, dtype=None, device=None, requires_grad=False) Tensor

返回大小为 size 的张量,并用1填充。 默认情况下,返回的张量与此张量具有相同的 torch.dtypetorch.device

参数

  • 大小 (python:int … )–定义输出张量形状的整数列表,元组或torch.Size

  • dtype (torch.dtype, optional) – 返回张量的所需类型。 默认: 如果是 None, 和 torch.dtype 一样

  • device (torch.device, optional) – 返回张量所在的设备。 默认: 如果是 None, 和 torch.device 一样

  • requires_grad (bool__, optional) – 返回的张量是否需要自动求导。 默认值:False

例:

  1. >>> tensor = torch.tensor((), dtype=torch.int32)
  2. >>> tensor.new_ones((2, 3))
  3. tensor([[ 1, 1, 1],
  4. [ 1, 1, 1]], dtype=torch.int32)

  1. new_zeros(size, dtype=None, device=None, requires_grad=False) Tensor

返回大小为 size 的张量,并用0填充。 默认情况下,返回的张量与此张量具有相同的 torch.dtypetorch.device

参数

  • size (python:int…) – a list, tuple, or torch.Size of integers defining the shape of the output tensor.

  • dtype (torch.dtype, optional) – 返回张量的所需类型。 默认值:如果为 None,则与此张量相同的 torch.dtype

  • device (torch.device, optional) – 返回张量的所需设备。 默认值:如果为 None,则与此张量相同的 torch.device

  • requires_grad (bool__, optional) – 返回的张量是否需要自动求导。 默认值:False

例:

  1. >>> tensor = torch.tensor((), dtype=torch.float64)
  2. >>> tensor.new_zeros((2, 3))
  3. tensor([[ 0., 0., 0.],
  4. [ 0., 0., 0.]], dtype=torch.float64)
  1. is_cuda

如果张量存储在 GPU 上,则为True,否则为False

  1. device

张量所在的 torch.device

  1. grad

此属性默认为None,并在首次调用 backward() 计算self的梯度时成为张量。 然后,该属性将包含计算出的梯度以及 backward()返回的梯度值,然后进行梯度累加。

  1. ndim

dim() 的别名

  1. T

这个张量的尺寸是否颠倒了吗?

如果nx中的尺寸数,则x.T等效于x.permute(n-1, n-2, ..., 0)


  1. abs() Tensor

参见 torch.abs()


  1. abs_() Tensor

就地版本的 abs()


  1. acos() Tensor

参见 torch.acos()


  1. acos_() Tensor

就地版本的 acos()


  1. add(value) Tensor

add(value = 1,other)->张量

参见 torch.add()


  1. add_(value) Tensor

add_(value = 1,other)->张量

就地版本的 add()


  1. addbmm(beta=1, alpha=1, batch1, batch2) Tensor

参见 torch.addbmm()


  1. addbmm_(beta=1, alpha=1, batch1, batch2) Tensor

就地版本的 addbmm()


  1. addcdiv(value=1, tensor1, tensor2) Tensor

参见 torch.addcdiv()


  1. addcdiv_(value=1, tensor1, tensor2) Tensor

就地版本的 addcdiv()


  1. addcmul(value=1, tensor1, tensor2) Tensor

参见 torch.addcmul()


  1. addcmul_(value=1, tensor1, tensor2) Tensor

就地版本的 addcmul()


  1. addmm(beta=1, alpha=1, mat1, mat2) Tensor

参见 torch.addmm()


  1. addmm_(beta=1, alpha=1, mat1, mat2) Tensor

就地版本的 addmm()


  1. addmv(beta=1, alpha=1, mat, vec) Tensor

参见 torch.addmv()


  1. addmv_(beta=1, alpha=1, mat, vec) Tensor

就地版本的 addmv()


  1. addr(beta=1, alpha=1, vec1, vec2) Tensor

参见 torch.addr()


  1. addr_(beta=1, alpha=1, vec1, vec2) Tensor

就地版本的 addr()


  1. allclose(other, rtol=1e-05, atol=1e-08, equal_nan=False) Tensor

参见 torch.allclose()


  1. angle() Tensor

参见 torch.angle()


  1. apply_(callable) Tensor

将函数callable应用于张量中的每个元素,并用callable返回的值替换每个元素。

注意

此功能仅适用于 CPU 张量,不应在需要高性能的代码段中使用。


  1. argmax(dim=None, keepdim=False) LongTensor

参见 torch.argmax()


  1. argmin(dim=None, keepdim=False) LongTensor

参见 torch.argmin()


  1. argsort(dim=-1, descending=False) LongTensor

参见:func: <cite>torch.argsort</cite>


  1. asin() Tensor

参见 torch.asin()


  1. asin_() Tensor

就地版本的 asin()


  1. as_strided(size, stride, storage_offset=0) Tensor

参见 torch.as_strided()


  1. atan() Tensor

参见 torch.atan()


  1. atan2(other) Tensor

参见 torch.atan2()


  1. atan2_(other) Tensor

就地版本的 atan2()


  1. atan_() Tensor

就地版本的 atan()


  1. backward(gradient=None, retain_graph=None, create_graph=False)

计算当前张量的梯度 w.r.t. 图叶。

该图使用链式法则进行区分。 如果张量是非标量的(即其数据具有多个元素)并且需要梯度,则该函数还需要指定gradient。 它应该是匹配类型和位置的张量,其中包含微分函数 w.r.t 的梯度。 self

此函数是叶子梯度累加-调用它之前可能需要将它们归零。

参数

  • gradient (tensor Tensor None)– 梯度 w.r.t. 张量。 如果它是张量,除非create_graph为 True,否则它将自动转换为不需要 grad 的张量。 无法为标量张量或不需要等级的张量指定任何值。 如果 None 值可以接受,那么此参数是可选的。

  • retian_graph (bool 可选)– 如果False,则用于计算等级的图形将被释放。 请注意,几乎在所有情况下都不需要将此选项设置为 True,并且通常可以以更有效的方式解决它。 默认为create_graph的值。

  • create_graph (bool 可选)– 如果True,则将构造导数图,从而允许计算高阶导数产品。 默认为False


  1. baddbmm(beta=1, alpha=1, batch1, batch2) Tensor

参见 torch.baddbmm()


  1. baddbmm_(beta=1, alpha=1, batch1, batch2) Tensor

就地版本的 baddbmm()


  1. bernoulli(*, generator=None) Tensor

返回结果张量,其中每个$result[i]$从$Bernoulli(self[i])$中独立采样。 self必须具有浮点dtype,结果将具有相同的dtype

参见 torch.bernoulli()


  1. bernoulli_(p=0.5, *, generator=None) Tensor

用$Bernoulli(p)$的独立样本填充self的每个位置。 self可以具有整数dtype


  1. bfloat16() Tensor

self.bfloat16()等效于self.to(torch.bfloat16)。 参见 to()


  1. bincount(weights=None, minlength=0) Tensor

参见 torch.bincount()


  1. bitwise_not() Tensor

参见 torch.bitwise_not()


  1. bitwise_not_() Tensor

就地版本的 bitwise_not()


  1. bitwise_xor() Tensor

参见 torch.bitwise_xor()


  1. bitwise_xor_() Tensor

就地版本的 bitwise_xor()


  1. bmm(batch2) Tensor

参见 torch.bmm()


  1. bool() Tensor

self.bool()等效于self.to(torch.bool)。 参见 to()


  1. byte() Tensor

self.byte()等效于self.to(torch.uint8)。 参见 to()


  1. cauchy_(median=0, sigma=1, *, generator=None) Tensor

用从柯西分布中得出的数字填充张量:

f(x)=\frac {1}{\pi}\frac {\sigma}{(x-median)^2+\sigma^2}


  1. ceil() Tensor

参见 torch.ceil()


  1. ceil_() Tensor

就地版本的 ceil()


  1. char() Tensor

self.char()等效于self.to(torch.int8)。 参见 to()


  1. cholesky(upper=False) Tensor

参见 torch.cholesky()


  1. cholesky_inverse(upper=False) Tensor

参见 torch.cholesky_inverse()


  1. cholesky_solve(input2, upper=False) Tensor

参见 torch.cholesky_solve()


  1. chunk(chunks, dim=0) List of Tensors

参见 torch.chunk()


  1. clamp(min, max) Tensor

参见 torch.clamp()


  1. clamp_(min, max) Tensor

就地版本的 clamp()


  1. clone() Tensor

返回self张量的副本。 该副本的大小和数据类型与self相同。

注意

copy_()不同,此功能记录在计算图中。 传播到克隆张量的渐变将传播到原始张量。


  1. contiguous() Tensor

返回包含与self张量相同的数据的连续张量。 如果self张量是连续的,则此函数返回self张量。


  1. copy_(src, non_blocking=False) Tensor

将元素从src复制到self张量并返回self

src张量必须与self张量一起广播。 它可以具有不同的数据类型,也可以位于不同的设备上。

参数

  • src (tensor)–要从中复制的源张量

  • non_blocking (bool )–如果True并且此副本位于 CPU 和 GPU 之间,则该副本可能相对于主机异步发生。 在其他情况下,此参数无效。


  1. conj() Tensor

参见 torch.conj()


  1. cos() Tensor

参见 torch.cos()


  1. cos_() Tensor

就地版本的 cos()


  1. cosh() Tensor

参见 torch.cosh()


  1. cosh_() Tensor

就地版本的 cosh()


  1. cpu() Tensor

返回此对象在 CPU 内存中的副本。

如果该对象已经在 CPU 内存中并且在正确的设备上,则不执行任何复制操作并返回原始对象。


  1. cross(other, dim=-1) Tensor

参见 torch.cross()


  1. cuda(device=None, non_blocking=False) Tensor

返回此对象在 CUDA 内存中的副本。

如果此对象已经在 CUDA 内存中并且在正确的设备上,则不执行任何复制,并返回原始对象。

参数

  • device (torch.device) – 目标 GPU 设备。 默认为当前 CUDA 设备。

  • non_blocking (bool ) – 如果True并且源位于固定内存中,则副本将相对于主机是异步的。 否则,该参数无效。 默认值:False


  1. cumprod(dim, dtype=None) Tensor

参见 torch.cumprod()


  1. cumsum(dim, dtype=None) Tensor

参见 torch.cumsum()


  1. data_ptr() int

返回self张量的第一个元素的地址。


  1. dequantize() Tensor

给定量化的张量,对其进行反量化,然后返回反量化后的浮点张量。


  1. det() Tensor

参见 torch.det()


  1. dense_dim() int

如果self是稀疏的 COO 张量(即torch.sparse_coo布局),则返回密集尺寸的数量。 否则,将引发错误。

另请参见 Tensor.sparse_dim()


  1. detach()

返回与当前图形分离的新 Tensor。

结果将永远不需要梯度。

注意

返回的 Tensor 与原始 Tensor 共享相同的存储。 可以看到对它们中的任何一个的就地修改,并且可能触发正确性检查中的错误。 重要说明:以前,就地大小/步幅/存储更改(例如 resize/_resize_as/set/_transpose) 返回的张量也会更新原始张量。 现在,这些就地更改将不再更新原始张量,而将触发错误。 对于稀疏张量:原位索引 / 值更改(例如 zero_/_copy/_add)将不会再更新原始张量, 而是触发错误。


  1. detach_()

从创建它的图形中分离张量,使其成为一片叶子。 视图不能就地分离。


  1. diag(diagonal=0) Tensor

参见 torch.diag()


  1. diag_embed(offset=0, dim1=-2, dim2=-1) Tensor

参见 torch.diag_embed()


  1. diagflat(offset=0) Tensor

参见 torch.diagflat()


  1. diagonal(offset=0, dim1=0, dim2=1) Tensor

参见 torch.diagonal()


  1. fill_diagonal_(fill_value, wrap=False) Tensor

填充具有至少 2 维的张量的主对角线。 当> 2 变暗时,所有输入尺寸必须相等。 此函数就地修改输入张量,并返回输入张量。

参数

  • fill_value (标量)– 填充值

  • wrap (bool ) – 对角线“包裹”在高列的 N 列之后。

例:

  1. >>> a = torch.zeros(3, 3)
  2. >>> a.fill_diagonal_(5)
  3. tensor([[5., 0., 0.],
  4. [0., 5., 0.],
  5. [0., 0., 5.]])
  6. >>> b = torch.zeros(7, 3)
  7. >>> b.fill_diagonal_(5)
  8. tensor([[5., 0., 0.],
  9. [0., 5., 0.],
  10. [0., 0., 5.],
  11. [0., 0., 0.],
  12. [0., 0., 0.],
  13. [0., 0., 0.],
  14. [0., 0., 0.]])
  15. >>> c = torch.zeros(7, 3)
  16. >>> c.fill_diagonal_(5, wrap=True)
  17. tensor([[5., 0., 0.],
  18. [0., 5., 0.],
  19. [0., 0., 5.],
  20. [0., 0., 0.],
  21. [5., 0., 0.],
  22. [0., 5., 0.],
  23. [0., 0., 5.]])

  1. digamma() Tensor

参见 torch.digamma()


  1. digamma_() Tensor

就地版本的 digamma()


  1. dim() int

返回self张量的维数。


  1. dist(other, p=2) Tensor

参见 torch.dist()


  1. div(value) Tensor

参见 torch.div()


  1. div_(value) Tensor

就地版本的 div()


  1. dot(tensor2) Tensor

参见 torch.dot()


  1. double() Tensor

self.double()等效于self.to(torch.float64)。 参见 to()


  1. eig(eigenvectors=False) -> (Tensor, Tensor)

参见 torch.eig()


  1. element_size() int

返回单个元素的大小(以字节为单位)。

例:

  1. >>> torch.tensor([]).element_size()
  2. 4
  3. >>> torch.tensor([], dtype=torch.uint8).element_size()
  4. 1

  1. eq(other) Tensor

参见 torch.eq()


  1. eq_(other) Tensor

就地版本的 eq()


  1. equal(other) bool

参见 torch.equal()


  1. erf() Tensor

参见 torch.erf()


  1. erf_() Tensor

就地版本的 erf()


  1. erfc() Tensor

参见 torch.erfc()


  1. erfc_() Tensor

就地版本的 erfc()


  1. erfinv() Tensor

参见 torch.erfinv()


  1. erfinv_() Tensor

就地版本的 erfinv()


  1. exp() Tensor

参见 torch.exp()


  1. exp_() Tensor

就地版本的 exp()


  1. expm1() Tensor

参见 torch.expm1()


  1. expm1_() Tensor

就地版本的 expm1()


  1. expand(*sizes) Tensor

返回self张量的新视图,其中单例尺寸扩展为更大的尺寸。

将-1 传递为尺寸的大小表示不更改该尺寸的大小。

Tensor 也可以扩展到更大的尺寸,并且新尺寸将附加在前面。 对于新尺寸,尺寸不能设置为-1。

扩展张量不会分配新的内存,而只会在现有张量上创建一个新视图,其中通过将stride设置为 0,将尺寸为 1 的维扩展为更大的尺寸。尺寸为 1 的任何维都可以扩展为 不分配新内存的任意值。

参数

*大小(torch大小 python:int … )–所需的扩展大小

警告

扩展张量的一个以上元素可以引用单个存储位置。 结果,就地操作(尤其是矢量化的操作)可能会导致错误的行为。 如果需要写张量,请先克隆它们。

例:

  1. >>> x = torch.tensor([[1], [2], [3]])
  2. >>> x.size()
  3. torch.Size([3, 1])
  4. >>> x.expand(3, 4)
  5. tensor([[ 1, 1, 1, 1],
  6. [ 2, 2, 2, 2],
  7. [ 3, 3, 3, 3]])
  8. >>> x.expand(-1, 4) # -1 means not changing the size of that dimension
  9. tensor([[ 1, 1, 1, 1],
  10. [ 2, 2, 2, 2],
  11. [ 3, 3, 3, 3]])

  1. expand_as(other) Tensor

将该张量扩展为与other相同的大小。 self.expand_as(other)等效于self.expand(other.size())

有关expand的更多信息,请参见 expand()

参数

其他 (torch.Tensor)–结果张量的大小与other相同。


  1. exponential_(lambd=1, *, generator=None) Tensor

用从指数分布中绘制的元素填充self张量:

f(x)=\lambda e^{-\lambda x}


  1. fft(signal_ndim, normalized=False) Tensor

参见 torch.fft()


  1. fill_(value) Tensor

用指定值填充self张量。


  1. flatten(input, start_dim=0, end_dim=-1) Tensor

参见 torch.flatten()


  1. flip(dims) Tensor

参见 torch.flip()


  1. float() Tensor

self.float()等效于self.to(torch.float32)。 参见 to()


  1. floor() Tensor

参见 torch.floor()


  1. floor_() Tensor

就地版本的 floor()


  1. fmod(divisor) Tensor

参见 torch.fmod()


  1. fmod_(divisor) Tensor

就地版本的 fmod()


  1. frac() Tensor

参见 torch.frac()


  1. frac_() Tensor

就地版本的 frac()


  1. gather(dim, index) Tensor

参见 torch.gather()


  1. ge(other) Tensor

参见 torch.ge()


  1. ge_(other) Tensor

就地版本的 ge()


  1. geometric_(p, *, generator=None) Tensor

用从几何分布中绘制的元素填充self张量:

f(X=k)=p^{k-1}(1-p)


  1. geqrf() -> (Tensor, Tensor)

参见 torch.geqrf()


  1. ger(vec2) Tensor

参见 torch.ger()


  1. get_device() -> Device ordinal (Integer)

对于 CUDA 张量,此函数返回张量所在的 GPU 的设备序号。 对于 CPU 张量,将引发错误。

例:

  1. >>> x = torch.randn(3, 4, 5, device='cuda:0')
  2. >>> x.get_device()
  3. 0
  4. >>> x.cpu().get_device() # RuntimeError: get_device is not implemented for type torch.FloatTensor

  1. gt(other) Tensor

参见 torch.gt()


  1. gt_(other) Tensor

就地版本的 gt()


  1. half() Tensor

self.half()等效于self.to(torch.float16)。 参见 to()


  1. hardshrink(lambd=0.5) Tensor

参见 torch.nn.functional.hardshrink()


  1. histc(bins=100, min=0, max=0) Tensor

参见 torch.histc()


  1. ifft(signal_ndim, normalized=False) Tensor

参见 torch.ifft()


  1. imag() Tensor

参见 torch.imag()


  1. index_add_(dim, index, tensor) Tensor

通过按index中给定的顺序添加索引,将 tensor 的元素累积到self张量中。 例如,如果dim == 0index[i] == j,则将的第itensor 添加到self的第j行。

tensordim 尺寸必须与index的长度(必须为矢量)的尺寸相同,并且所有其他尺寸必须与self ],否则将引发错误。

注意

使用 CUDA 后端时,此操作可能会导致不确定的行为,不容易关闭。 有关背景,请参见重现性的注释。

参数

  • dim (python:int )–索引所沿的维度

  • 索引 (LongTensor )– tensor 的索引

  • 张量 (tensor)–张量包含要添加的值

例:

  1. >>> x = torch.ones(5, 3)
  2. >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float)
  3. >>> index = torch.tensor([0, 4, 2])
  4. >>> x.index_add_(0, index, t)
  5. tensor([[ 2., 3., 4.],
  6. [ 1., 1., 1.],
  7. [ 8., 9., 10.],
  8. [ 1., 1., 1.],
  9. [ 5., 6., 7.]])

  1. index_add(dim, index, tensor) Tensor

torch.Tensor.index_add_() 的替代版本


  1. index_copy_(dim, index, tensor) Tensor

通过按index中给定的顺序选择索引,将 tensor 的元素复制到self张量中。 例如,如果dim == 0index[i] == j,则将 tensor 的第i行复制到self的第j行。

The dimth dimension of tensor must have the same size as the length of index (which must be a vector), and all other dimensions must match self, or an error will be raised.

参数

  • dim (python:int) – dimension along which to index

  • index (LongTensor) – indices of tensor to select from

  • 张量 (tensor)–张量包含要复制的值

例:

  1. >>> x = torch.zeros(5, 3)
  2. >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float)
  3. >>> index = torch.tensor([0, 4, 2])
  4. >>> x.index_copy_(0, index, t)
  5. tensor([[ 1., 2., 3.],
  6. [ 0., 0., 0.],
  7. [ 7., 8., 9.],
  8. [ 0., 0., 0.],
  9. [ 4., 5., 6.]])

  1. index_copy(dim, index, tensor) Tensor

torch.Tensor.index_copy_() 的替代版本


  1. index_fill_(dim, index, val) Tensor

通过按index中给定的顺序选择索引,用值val填充self张量的元素。

参数

  • dim (python:int) – dimension along which to index

  • 索引 (LongTensor )–填写的self张量索引

  • val (python:float )–要填充的值

  1. 例::
  1. >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float)
  2. >>> index = torch.tensor([0, 2])
  3. >>> x.index_fill_(1, index, -1)
  4. tensor([[-1., 2., -1.],
  5. [-1., 5., -1.],
  6. [-1., 8., -1.]])

  1. index_fill(dim, index, value) Tensor

torch.Tensor.index_fill_() 的替代版本


  1. index_put_(indices, value, accumulate=False) Tensor

使用在 indices 中指定的索引(张量的元组)将张量value的值放入张量self。 表达式tensor.index_put_(indices, value)等效于tensor[indices] = value。 返回self

如果accumulateTrue,则将 tensor 中的元素添加到self中。 如果 accumulate 为False,则在索引包含重复元素的情况下行为未定义。

参数

  • 索引(LongTensor 的元组)–用于索引<cite>自身</cite>的张量。

  • (tensor)–与<cite>自身</cite>相同类型的张量。

  • 累积 (bool )–是否累积


  1. index_put(indices, value, accumulate=False) Tensor

index_put_() 的替代版本


  1. index_select(dim, index) Tensor

参见 torch.index_select()


  1. indices() Tensor

如果self是稀疏的 COO 张量(即torch.sparse_coo布局),则返回包含的索引张量的视图。 否则,将引发错误。

另请参见 Tensor.values()

注意

只能在合并的稀疏张量上调用此方法。 有关详细信息,请参见Tensor.coalesce()


  1. int() Tensor

self.int()等效于self.to(torch.int32)。 参见 to()


  1. int_repr() Tensor

给定量化的 Tensor,self.int_repr()返回以 uint8_t 作为数据类型的 CPU Tensor,该数据类型存储给定 Tensor 的基础 uint8_t 值。


  1. inverse() Tensor

参见 torch.inverse()


  1. irfft(signal_ndim, normalized=False, onesided=True, signal_sizes=None) Tensor

参见 torch.irfft()


  1. is_contiguous() bool

如果self张量在内存中以 C 顺序连续,则返回 True。


  1. is_floating_point() bool

如果self的数据类型是浮点数据类型,则返回 True。

  1. is_leaf

按照惯例,所有具有 requires_gradFalse的张量将是叶张量。

对于具有 requires_grad (即True)的张量,如果它们是由用户创建的,则它们将是叶张量。 这意味着它们不是运算的结果,因此grad_fn为“无”。

在调用 backward() 期间,仅叶子张量会填充其 grad 。 要为非叶张量填充 grad ,可以使用 retain_grad()

例:

  1. >>> a = torch.rand(10, requires_grad=True)
  2. >>> a.is_leaf
  3. True
  4. >>> b = torch.rand(10, requires_grad=True).cuda()
  5. >>> b.is_leaf
  6. False
  7. # b was created by the operation that cast a cpu Tensor into a cuda Tensor
  8. >>> c = torch.rand(10, requires_grad=True) + 2
  9. >>> c.is_leaf
  10. False
  11. # c was created by the addition operation
  12. >>> d = torch.rand(10).cuda()
  13. >>> d.is_leaf
  14. True
  15. # d does not require gradients and so has no operation creating it (that is tracked by the autograd engine)
  16. >>> e = torch.rand(10).cuda().requires_grad_()
  17. >>> e.is_leaf
  18. True
  19. # e requires gradients and has no operations creating it
  20. >>> f = torch.rand(10, requires_grad=True, device="cuda")
  21. >>> f.is_leaf
  22. True
  23. # f requires grad, has no operation creating it

  1. is_pinned()

如果该张量驻留在固定的内存中,则返回 true。


  1. is_set_to(tensor) bool

如果此对象引用与 Torch C API 中相同的THTensor对象作为给定张量,则返回 True。


  1. is_shared()

检查张量是否在共享内存中。

CUDA 张量始终为True


  1. is_signed() bool

如果self的数据类型是带符号的数据类型,则返回 True。

  1. is_sparse

  1. item() number

返回此张量的值作为标准 Python 数。 这仅适用于具有一个元素的张量。 对于其他情况,请参见 tolist()

此操作不可区分。

例:

  1. >>> x = torch.tensor([1.0])
  2. >>> x.item()
  3. 1.0

  1. kthvalue(k, dim=None, keepdim=False) -> (Tensor, LongTensor)

参见 torch.kthvalue()


  1. le(other) Tensor

参见 torch.le()


  1. le_(other) Tensor

就地版本的 le()


  1. lerp(end, weight) Tensor

参见 torch.lerp()


  1. lerp_(end, weight) Tensor

就地版本的 lerp()


  1. lgamma() Tensor

参见 torch.lgamma()


  1. lgamma_() Tensor

就地版本的 lgamma()


  1. log() Tensor

参见 torch.log()


  1. log_() Tensor

就地版本的 log()


  1. logdet() Tensor

参见 torch.logdet()


  1. log10() Tensor

参见 torch.log10()


  1. log10_() Tensor

就地版本的 log10()


  1. log1p() Tensor

参见 torch.log1p()


  1. log1p_() Tensor

就地版本的 log1p()


  1. log2() Tensor

参见 torch.log2()


  1. log2_() Tensor

就地版本的 log2()


  1. log_normal_(mean=1, std=2, *, generator=None)

用对数正态分布中由给定平均值torch张量 - 图1和标准偏差torch张量 - 图2参数化的数字样本填充self张量。 请注意, meanstd 是基础正态分布的均值和标准偏差,而不是返回的正态分布:

f(x)=\frac {1}{x\sigma \sqrt {2\pi}}e^{-\frac {(lnx - \mu)^2}{2\sigma^2}}


  1. logsumexp(dim, keepdim=False) Tensor

参见 torch.logsumexp()


  1. logical_not() Tensor

参见 torch.logical_not()


  1. logical_not_() Tensor

就地版本的 logical_not()


  1. logical_xor() Tensor

参见 torch.logical_xor()


  1. logical_xor_() Tensor

就地版本的 logical_xor()


  1. long() Tensor

self.long()等效于self.to(torch.int64)。 参见 to()


  1. lstsq(A) -> (Tensor, Tensor)

参见 torch.lstsq()


  1. lt(other) Tensor

参见 torch.lt()


  1. lt_(other) Tensor

就地版本的 lt()


  1. lu(pivot=True, get_infos=False)

参见 torch.lu()


  1. lu_solve(LU_data, LU_pivots) Tensor

参见 torch.lu_solve()


  1. map_(tensor, callable)

self张量中的每个元素和给定的 tensor 应用callable,并将结果存储在self张量中。 self张量和给定的 tensor 必须是可广播的

callable应具有签名:

  1. def callable(a, b) -> number

  1. masked_scatter_(mask, source)

mask为 True 的位置将元素从source复制到self张量。 mask的形状必须是可广播的,并具有基础张量的形状。 source中的元素数量至少应与mask中的元素数量一样多。

参数

注意

maskself张量上运行,而不是在给定的source张量上运行。


  1. masked_scatter(mask, tensor) Tensor

torch.Tensor.masked_scatter_() 的替代版本


  1. masked_fill_(mask, value)

value填充self张量的元素,其中mask为 True。 mask的形状必须是可广播的,并具有基础张量的形状。

参数

  • mask (BoolTensor) – the boolean mask

  • (python:float )–要填写的值


  1. masked_fill(mask, value) Tensor

torch.Tensor.masked_fill_() 的替代版本


  1. masked_select(mask) Tensor

参见 torch.masked_select()


  1. matmul(tensor2) Tensor

参见 torch.matmul()


  1. matrix_power(n) Tensor

参见 torch.matrix_power()


  1. max(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor)

参见 torch.max()


  1. mean(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor)

参见 torch.mean()


  1. median(dim=None, keepdim=False) -> (Tensor, LongTensor)

参见 torch.median()


  1. min(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor)

参见 torch.min()


  1. mm(mat2) Tensor

参见 torch.mm()


  1. mode(dim=None, keepdim=False) -> (Tensor, LongTensor)

参见 torch.mode()


  1. mul(value) Tensor

参见 torch.mul()


  1. mul_(value)

就地版本的 mul()


  1. multinomial(num_samples, replacement=False, *, generator=None) Tensor

参见 torch.multinomial()


  1. mv(vec) Tensor

参见 torch.mv()


  1. mvlgamma(p) Tensor

参见 torch.mvlgamma()


  1. mvlgamma_(p) Tensor

就地版本的 mvlgamma()


  1. narrow(dimension, start, length) Tensor

参见 torch.narrow()

例:

  1. >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  2. >>> x.narrow(0, 0, 2)
  3. tensor([[ 1, 2, 3],
  4. [ 4, 5, 6]])
  5. >>> x.narrow(1, 1, 2)
  6. tensor([[ 2, 3],
  7. [ 5, 6],
  8. [ 8, 9]])

  1. narrow_copy(dimension, start, length) Tensor

Tensor.narrow() 相同,只是返回副本而不是共享存储。 这主要用于稀疏张量,它们没有共享存储的窄方法。 用dimemsion &gt; self.sparse_dim()调用narrow_copy`将返回缩小了相关密集尺寸的副本,并相应地更新了self.shape``。


  1. ndimension() int

Alias for dim()


  1. ne(other) Tensor

参见 torch.ne()


  1. ne_(other) Tensor

就地版本的 ne()


  1. neg() Tensor

参见 torch.neg()


  1. neg_() Tensor

就地版本的 neg()


  1. nelement() int

numel() 的别名


  1. nonzero() LongTensor

参见 torch.nonzero()


  1. norm(p='fro', dim=None, keepdim=False, dtype=None)

参见 torch.norm()


  1. normal_(mean=0, std=1, *, generator=None) Tensor

用由 meanstd 参数化的正态分布的元素样本填充self张量。


  1. numel() int

参见 torch.numel()


  1. numpy() numpy.ndarray

以 NumPy ndarray的形式返回self张量。 该张量和返回的ndarray共享相同的基础存储。 对self张量的更改将反映在ndarray中,反之亦然。


  1. orgqr(input2) Tensor

参见 torch.orgqr()


  1. ormqr(input2, input3, left=True, transpose=False) Tensor

参见 torch.ormqr()


  1. permute(*dims) Tensor

置换此张量的尺寸。

参数

*dims (python:int … ) – 所需的维度顺序

例:

  1. >>> x = torch.randn(2, 3, 5)
  2. >>> x.size()
  3. torch.Size([2, 3, 5])
  4. >>> x.permute(2, 0, 1).size()
  5. torch.Size([5, 2, 3])

  1. pin_memory() Tensor

将张量复制到固定的内存(如果尚未固定)。


  1. pinverse() Tensor

参见 torch.pinverse()


  1. polygamma(n) Tensor

参见 torch.polygamma()


  1. polygamma_(n) Tensor

就地版本的 polygamma()


  1. pow(exponent) Tensor

参见 torch.pow()


  1. pow_(exponent) Tensor

就地版本的 pow()


  1. prod(dim=None, keepdim=False, dtype=None) Tensor

参见 torch.prod()


  1. put_(indices, tensor, accumulate=False) Tensor

tensor 中的元素复制到索引指定的位置。 为了建立索引,将self张量视为一维张量。

If accumulate is True, the elements in tensor are added to self. If accumulate is False, the behavior is undefined if indices contain duplicate elements.

参数

  • 索引 (LongTensor )–自身索引

  • 张量 (tensor)–张量包含要复制的值

  • accumulate (bool) – whether to accumulate into self

例:

  1. >>> src = torch.tensor([[4, 3, 5],
  2. [6, 7, 8]])
  3. >>> src.put_(torch.tensor([1, 3]), torch.tensor([9, 10]))
  4. tensor([[ 4, 9, 5],
  5. [ 10, 7, 8]])

  1. qr(some=True) -> (Tensor, Tensor)

参见 torch.qr()


  1. qscheme() torch.qscheme

返回给定 QTensor 的量化方案。


  1. q_scale() float

给定一个通过线性(仿射)量化量化的张量,返回基础量化器()的比例尺。


  1. q_zero_point() int

给定一个通过线性(仿射)量化量化的张量,返回基础量化器()的 zero_point。


  1. q_per_channel_scales() Tensor

给定通过线性(仿射)每通道量化进行量化的张量,返回基础量化器的比例的张量。 它具有与张量的相应尺寸(来自 q_per_channel_axis)匹配的元素数量。


  1. q_per_channel_zero_points() Tensor

给定一个通过线性(仿射)每通道量化量化的张量,返回基础量化器的 zero_points 张量。 它具有与张量的相应尺寸(来自 q_per_channel_axis)匹配的元素数量。


  1. q_per_channel_axis() int

给定通过线性(仿射)每通道量化量化的张量,返回在其上应用每通道量化的尺寸索引。


  1. random_(from=0, to=None, *, generator=None) Tensor

用从[from, to - 1]上的离散均匀分布采样的数字填充self张量。 如果未指定,则这些值通常仅受self张量的数据类型限制。 但是,对于浮点类型,如果未指定,范围将为[0, 2^mantissa]以确保每个值都是可表示的。 例如, <cite>torch.tensor(1,dtype = torch.double).random_()</cite>在[0, 2^53]中将是统一的。


  1. reciprocal() Tensor

参见 torch.reciprocal()


  1. reciprocal_() Tensor

就地版本的 reciprocal()


  1. record_stream(stream)

确保在stream上排队的所有当前工作完成之前,张量存储器不会被其他张量重用。

注意

缓存分配器仅知道分配张量的流。 由于有了这种认识,它已经可以仅在一个流上正确管理张量的生命周期。 但是,如果在与原始流不同的流上使用张量,则分配器可能会意外地重用内存。 调用此方法可让分配器知道哪些流使用了张量。


  1. register_hook(hook)

注册一个倒钩。

每当计算相对于张量的梯度时,都会调用该挂钩。 挂钩应具有以下签名:

  1. hook(grad) -> Tensor or None

挂钩不应修改其自变量,但可以选择返回一个新的渐变,该渐变将代替 grad 使用。

此函数返回带有方法handle.remove()的句柄,该方法可将钩子从模块中移除。

例:

  1. >>> v = torch.tensor([0., 0., 0.], requires_grad=True)
  2. >>> h = v.register_hook(lambda grad: grad * 2) # double the gradient
  3. >>> v.backward(torch.tensor([1., 2., 3.]))
  4. >>> v.grad
  5. 2
  6. 4
  7. 6
  8. [torch.FloatTensor of size (3,)]
  9. >>> h.remove() # removes the hook

  1. remainder(divisor) Tensor

参见 torch.remainder()


  1. remainder_(divisor) Tensor

就地版本的 remainder()


  1. real() Tensor

参见 torch.real()


  1. renorm(p, dim, maxnorm) Tensor

参见 torch.renorm()


  1. renorm_(p, dim, maxnorm) Tensor

就地版本的 renorm()


  1. repeat(*sizes) Tensor

沿指定尺寸重复此张量。

expand() 不同,此功能复制张量的数据。

警告

torch.repeat()的行为与 numpy.repeat 不同,但更类似于 numpy.tile 。 对于类似于 <cite>numpy.repeat</cite> 的运算符,请参见 torch.repeat_interleave()

参数

大小(torch大小 python:int … )–在每个维度上重复此张量的次数

例:

  1. >>> x = torch.tensor([1, 2, 3])
  2. >>> x.repeat(4, 2)
  3. tensor([[ 1, 2, 3, 1, 2, 3],
  4. [ 1, 2, 3, 1, 2, 3],
  5. [ 1, 2, 3, 1, 2, 3],
  6. [ 1, 2, 3, 1, 2, 3]])
  7. >>> x.repeat(4, 2, 1).size()
  8. torch.Size([4, 2, 3])

  1. repeat_interleave(repeats, dim=None) Tensor

参见 torch.repeat_interleave()

  1. requires_grad

如果需要为此张量计算梯度,则为True,否则为False

注意

需要为张量计算梯度的事实并不意味着将填充 grad 属性,有关更多详细信息,请参见 is_leaf


  1. requires_grad_(requires_grad=True) Tensor

更改 autograd 是否应记录该张量上的操作:适当地设置此张量的 requires_grad 属性。 返回此张量。

requires_grad_() 的主要用例是告诉 autograd 在 Tensor tensor上开始记录操作。 如果tensor具有requires_grad=False(因为它是通过 DataLoader 获得的,或者需要进行预处理或初始化),则tensor.requires_grad_()将其设置为使 autograd 将开始在tensor上记录操作。

参数

require_grad (bool )–如果 autograd 应该在该张量上记录操作。 默认值:True

例:

  1. >>> # Let's say we want to preprocess some saved weights and use
  2. >>> # the result as new weights.
  3. >>> saved_weights = [0.1, 0.2, 0.3, 0.25]
  4. >>> loaded_weights = torch.tensor(saved_weights)
  5. >>> weights = preprocess(loaded_weights) # some function
  6. >>> weights
  7. tensor([-0.5503, 0.4926, -2.1158, -0.8303])
  8. >>> # Now, start to record operations done to weights
  9. >>> weights.requires_grad_()
  10. >>> out = weights.pow(2).sum()
  11. >>> out.backward()
  12. >>> weights.grad
  13. tensor([-1.1007, 0.9853, -4.2316, -1.6606])

  1. reshape(*shape) Tensor

返回具有与self相同的数据和元素数量但具有指定形状的张量。 如果shape与当前形状兼容,则此方法返回一个视图。 当可以返回视图时,请参见 torch.Tensor.view()

参见 torch.reshape()

参数

形状 (python:ints 的元组 python:int … )–所需的形状


  1. reshape_as(other) Tensor

以与other相同的形状返回此张量。 self.reshape_as(other)等效于self.reshape(other.sizes())。 如果other.sizes()与当前形状兼容,则此方法返回视图。 何时可以返回视图,请参见 torch.Tensor.view()

有关reshape的更多信息,请参见 reshape()

参数

其他 (torch.Tensor)–结果张量具有与other相同的形状。


  1. resize_(*sizes) Tensor

self张量调整为指定大小。 如果元素数量大于当前存储大小,那么将调整基础存储的大小以适合新的元素数量。 如果元素数较小,则基础存储不会更改。 现有元素将保留,但任何新内存均未初始化。

警告

这是一种底层方法。 将存储重新解释为 C 连续的,而忽略当前步幅(除非目标大小等于当前大小,在这种情况下,张量保持不变)。 对于大多数目的,您将改为使用 view() (检查连续性),或使用 reshape() (如果需要,可复制数据)。 要使用自定义步幅就地更改大小,请参见 set_()

参数

大小(torch大小 python:int … )–所需大小

例:

  1. >>> x = torch.tensor([[1, 2], [3, 4], [5, 6]])
  2. >>> x.resize_(2, 2)
  3. tensor([[ 1, 2],
  4. [ 3, 4]])

  1. resize_as_(tensor) Tensor

self张量调整为与指定的 tensor 相同的大小。 这等效于self.resize_(tensor.size())


  1. retain_grad()

为非叶张量启用.grad 属性。


  1. rfft(signal_ndim, normalized=False, onesided=True) Tensor

参见 torch.rfft()


  1. roll(shifts, dims) Tensor

参见 torch.roll()


  1. rot90(k, dims) Tensor

参见 torch.rot90()


  1. round() Tensor

参见 torch.round()


  1. round_() Tensor

就地版本的 round()


  1. rsqrt() Tensor

参见 torch.rsqrt()


  1. rsqrt_() Tensor

就地版本的 rsqrt()


  1. scatter(dim, index, source) Tensor

torch.Tensor.scatter_() 的替代版本


  1. scatter_(dim, index, src) Tensor

将张量src中的所有值写入index张量中指定的索引处的self中。 对于src中的每个值,其输出索引由dimension != dimsrc中的索引以及dimension = dimindex中的相应值指定。

对于 3-D 张量,self更新为:

  1. self[index[i][j][k]][j][k] = src[i][j][k] # if dim == 0
  2. self[i][index[i][j][k]][k] = src[i][j][k] # if dim == 1
  3. self[i][j][index[i][j][k]] = src[i][j][k] # if dim == 2

这是 gather() 中描述的方式的相反操作。

selfindexsrc(如果是张量)应具有相同数量的尺寸。 还要求对于所有尺寸d均为index.size(d) &lt;= src.size(d),并且对于所有尺寸d != dim均要求index.size(d) &lt;= self.size(d)

此外,对于 gather()index的值必须介于0self.size(dim) - 1之间,且沿指定尺寸 dim 必须是唯一的。

参数

  • dim (python:int ) – 沿其索引的轴

  • index (LongTensor ) – 要散布的元素的索引可以为空或 src 的大小相同。 如果为空,则操作返回标识

  • src (tensor) – 要散布的源元素,如果未指定

  • value (python:float ) – 要分散的源元素,如果未指定src

例:

  1. >>> x = torch.rand(2, 5)
  2. >>> x
  3. tensor([[ 0.3992, 0.2908, 0.9044, 0.4850, 0.6004],
  4. [ 0.5735, 0.9006, 0.6797, 0.4152, 0.1732]])
  5. >>> torch.zeros(3, 5).scatter_(0, torch.tensor([[0, 1, 2, 0, 0], [2, 0, 0, 1, 2]]), x)
  6. tensor([[ 0.3992, 0.9006, 0.6797, 0.4850, 0.6004],
  7. [ 0.0000, 0.2908, 0.0000, 0.4152, 0.0000],
  8. [ 0.5735, 0.0000, 0.9044, 0.0000, 0.1732]])
  9. >>> z = torch.zeros(2, 4).scatter_(1, torch.tensor([[2], [3]]), 1.23)
  10. >>> z
  11. tensor([[ 0.0000, 0.0000, 1.2300, 0.0000],
  12. [ 0.0000, 0.0000, 0.0000, 1.2300]])

  1. scatter_add_(dim, index, other) Tensor

将张量other中的所有值添加到index张量中指定的索引处的self中,其方式与 scatter_() 相似。 对于other中的每个值,将其添加到self中的索引,该索引由dimension != dim中的other中的索引和dimension = dim中的index中的对应值指定。

For a 3-D tensor, self is updated as:

  1. self[index[i][j][k]][j][k] += other[i][j][k] # if dim == 0
  2. self[i][index[i][j][k]][k] += other[i][j][k] # if dim == 1
  3. self[i][j][index[i][j][k]] += other[i][j][k] # if dim == 2

selfindexother应具有相同的尺寸数。 还要求对于所有尺寸d均为index.size(d) &lt;= other.size(d),并且对于所有尺寸d != dim均要求index.size(d) &lt;= self.size(d)

注意

When using the CUDA backend, this operation may induce nondeterministic behaviour that is not easily switched off. Please see the 注意s on Reproducibility for background.

参数

  • dim (python:int) – the axis along which to index

  • index (LongTensor ) – 分散和添加元素的索引,可以为空或 src 大小相同。 为空时,该操作将返回标识。

  • other (tensor) – 分散和添加的源元素

例:

  1. >>> x = torch.rand(2, 5)
  2. >>> x
  3. tensor([[0.7404, 0.0427, 0.6480, 0.3806, 0.8328],
  4. [0.7953, 0.2009, 0.9154, 0.6782, 0.9620]])
  5. >>> torch.ones(3, 5).scatter_add_(0, torch.tensor([[0, 1, 2, 0, 0], [2, 0, 0, 1, 2]]), x)
  6. tensor([[1.7404, 1.2009, 1.9154, 1.3806, 1.8328],
  7. [1.0000, 1.0427, 1.0000, 1.6782, 1.0000],
  8. [1.7953, 1.0000, 1.6480, 1.0000, 1.9620]])

  1. scatter_add(dim, index, source) Tensor

torch.Tensor.scatter_add_() 的替代版本


  1. select(dim, index) Tensor

沿选定维度在给定索引处切片self张量。 该函数返回一个张量,其中给定尺寸被移除。

参数

  • dim (python:int )–切片的尺寸

  • 索引 (python:int )–要选择的索引

注意

select() 相当于切片。 例如,tensor.select(0, index)等效于tensor[index]tensor.select(2, index)等效于tensor[:,:,index]


  1. set_(source=None, storage_offset=0, size=None, stride=None) Tensor

设置基础存储空间,大小和跨度。 如果source是张量,则self张量将与source共享相同的存储空间并具有相同的大小和跨度。 一个张量中元素的变化将反映在另一个张量中。

如果sourceStorage,则该方法设置基础存储,偏移,大小和跨度。

参数

  • (tensor 存储器)–使用的张量或存储器

  • storage_offset (python:int 可选)–存储中的偏移量

  • 大小(torch大小 可选)–所需大小。 默认为源大小。

  • 步幅(元组 可选)–所需的步幅。 默认为 C 连续跨步。


  1. share_memory_()

将基础存储移动到共享内存。

如果基础存储已经在共享内存中并且用于 CUDA 张量,则此操作不可操作。 共享内存中的张量无法调整大小。


  1. short() Tensor

self.short()等效于self.to(torch.int16)。 参见 to()


  1. sigmoid() Tensor

参见 torch.sigmoid()


  1. sigmoid_() Tensor

就地版本的 sigmoid()


  1. sign() Tensor

参见 torch.sign()


  1. sign_() Tensor

就地版本的 sign()


  1. sin() Tensor

参见 torch.sin()


  1. sin_() Tensor

就地版本的 sin()


  1. sinh() Tensor

参见 torch.sinh()


  1. sinh_() Tensor

就地版本的 sinh()


  1. size() torch.Size

返回self张量的大小。 返回的值是tuple的子类。

例:

  1. >>> torch.empty(3, 4, 5).size()
  2. torch.Size([3, 4, 5])

  1. slogdet() -> (Tensor, Tensor)

参见 torch.slogdet()


  1. solve(A) Tensor, Tensor

参见 torch.solve()


  1. sort(dim=-1, descending=False) -> (Tensor, LongTensor)

参见 torch.sort()


  1. split(split_size, dim=0)

参见 torch.split()


  1. sparse_mask(input, mask) Tensor

返回一个新的 SparseTensor,其 Tensor input中的值被mask的索引过滤,并且值被忽略。 inputmask必须具有相同的形状。

参数

  • input (tensor)–输入张量

  • mask (SparseTensor )–我们根据其索引过滤input的 SparseTensor

例:

  1. >>> nnz = 5
  2. >>> dims = [5, 5, 2, 2]
  3. >>> I = torch.cat([torch.randint(0, dims[0], size=(nnz,)),
  4. torch.randint(0, dims[1], size=(nnz,))], 0).reshape(2, nnz)
  5. >>> V = torch.randn(nnz, dims[2], dims[3])
  6. >>> size = torch.Size(dims)
  7. >>> S = torch.sparse_coo_tensor(I, V, size).coalesce()
  8. >>> D = torch.randn(dims)
  9. >>> D.sparse_mask(S)
  10. tensor(indices=tensor([[0, 0, 0, 2],
  11. [0, 1, 4, 3]]),
  12. values=tensor([[[ 1.6550, 0.2397],
  13. [-0.1611, -0.0779]],
  14. [[ 0.2326, -1.0558],
  15. [ 1.4711, 1.9678]],
  16. [[-0.5138, -0.0411],
  17. [ 1.9417, 0.5158]],
  18. [[ 0.0793, 0.0036],
  19. [-0.2569, -0.1055]]]),
  20. size=(5, 5, 2, 2), nnz=4, layout=torch.sparse_coo)

  1. sparse_dim() int

如果self是稀疏的 COO 张量(即torch.sparse_coo布局),则返回稀疏维度的数量。 否则,将引发错误。

另请参见 Tensor.dense_dim()


  1. sqrt() Tensor

参见 torch.sqrt()


  1. sqrt_() Tensor

就地版本的 sqrt()


  1. squeeze(dim=None) Tensor

参见 torch.squeeze()


  1. squeeze_(dim=None) Tensor

就地版本的 squeeze()


  1. std(dim=None, unbiased=True, keepdim=False) Tensor

参见 torch.std()


  1. stft(n_fft, hop_length=None, win_length=None, window=None, center=True, pad_mode='reflect', normalized=False, onesided=True)

参见 torch.stft()

警告

此功能在版本 0.4.1 更改了签名。 使用前一个签名进行调用可能会导致错误或返回错误的结果。


  1. storage() torch.Storage

返回基础存储。


  1. storage_offset() int

根据存储元素的数量(不是字节),返回基础存储中的self张量偏移量。

例:

  1. >>> x = torch.tensor([1, 2, 3, 4, 5])
  2. >>> x.storage_offset()
  3. 0
  4. >>> x[3:].storage_offset()
  5. 3

  1. storage_type() type

返回基础存储的类型。


  1. stride(dim) tuple or int

返回self张量的步幅。

跨度是在指定尺寸 dim 中从一个元素跳至下一元素所需的跳跃。 当未传递任何参数时,将返回所有跨度的元组。否则,将返回整数值作为特定维度 dim 中的跨度。

参数

dim (python:int 可选)– 需要跨度的所需尺寸

例:

  1. >>> x = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
  2. >>> x.stride()
  3. (5, 1)
  4. >>>x.stride(0)
  5. 5
  6. >>> x.stride(-1)
  7. 1

  1. sub(value, other) Tensor

self张量中减去标量或张量。 如果同时指定了valueother,则在使用前other的每个元素都会按value缩放。

other是张量时,other的形状必须是可广播的,并具有基础张量的形状。


  1. sub_(x) Tensor

就地版本的 sub()


  1. sum(dim=None, keepdim=False, dtype=None) Tensor

参见 torch.sum()


  1. sum_to_size(*size) Tensor

this张量与 size 相加。 size 必须可广播到this张量大小。

参数

大小 (python:int … )–定义输出张量形状的整数序列。


  1. svd(some=True, compute_uv=True) -> (Tensor, Tensor, Tensor)

参见 torch.svd()


  1. symeig(eigenvectors=False, upper=True) -> (Tensor, Tensor)

参见 torch.symeig()


  1. t() Tensor

参见 torch.t()


  1. t_() Tensor

就地版本的 t()


  1. to(*args, **kwargs) Tensor

执行 Tensor dtype 和/或设备转换。 torch.dtypetorch.device 是从self.to(*args, **kwargs)的论点推论出来的。

注意

如果self张量已经具有正确的 torch.dtypetorch.device ,则返回self。 否则,返回的张量是self与所需 torch.dtypetorch.device 的副本。

以下是调用to的方法:


  1. to(dtype, non_blocking=False, copy=False) Tensor

返回具有指定dtype的张量


  1. to(device=None, dtype=None, non_blocking=False, copy=False) Tensor

返回具有指定 device 和(可选)dtype的张量。 如果dtypeNone,则推断为self.dtype。 当non_blocking时,如果可能,尝试相对于主机进行异步转换,例如,将具有固定内存的 CPU 张量转换为 CUDA 张量。 设置copy时,即使张量已经匹配所需的转换,也会创建新的张量。


  1. to(other, non_blocking=False, copy=False) Tensor

返回与张量other相同的 torch.dtypetorch.device 的张量。 当non_blocking时,如果可能,尝试相对于主机进行异步转换,例如,将具有固定内存的 CPU 张量转换为 CUDA 张量。 设置copy时,即使张量已经与所需的转换匹配,也会创建新的张量。

例:

  1. >>> tensor = torch.randn(2, 2) # Initially dtype=float32, device=cpu
  2. >>> tensor.to(torch.float64)
  3. tensor([[-0.5044, 0.0005],
  4. [ 0.3310, -0.0584]], dtype=torch.float64)
  5. >>> cuda0 = torch.device('cuda:0')
  6. >>> tensor.to(cuda0)
  7. tensor([[-0.5044, 0.0005],
  8. [ 0.3310, -0.0584]], device='cuda:0')
  9. >>> tensor.to(cuda0, dtype=torch.float64)
  10. tensor([[-0.5044, 0.0005],
  11. [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0')
  12. >>> other = torch.randn((), dtype=torch.float64, device=cuda0)
  13. >>> tensor.to(other, non_blocking=True)
  14. tensor([[-0.5044, 0.0005],
  15. [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0')

  1. to_mkldnn() Tensor

返回torch.mkldnn布局中的张量的副本。


  1. take(indices) Tensor

参见 torch.take()


  1. tan() Tensor

参见 torch.tan()


  1. tan_() Tensor

就地版本的 tan()


  1. tanh() Tensor

参见 torch.tanh()


  1. tanh_() Tensor

就地版本的 tanh()


  1. tolist()

” tolist()->列表或编号

将张量作为(嵌套的)列表返回。 对于标量,将返回标准 Python 编号,就像 item() 一样。 如有必要,张量会先自动移至 CPU。

This operation is not differentiable.

例子:

  1. >>> a = torch.randn(2, 2)
  2. >>> a.tolist()
  3. [[0.012766935862600803, 0.5415473580360413],
  4. [-0.08909505605697632, 0.7729271650314331]]
  5. >>> a[0,0].tolist()
  6. 0.012766935862600803

  1. topk(k, dim=None, largest=True, sorted=True) -> (Tensor, LongTensor)

参见 torch.topk()


  1. to_sparse(sparseDims) Tensor

返回张量的稀疏副本。 PyTorch 支持坐标格式的稀疏张量。

参数

sparseDims (python:int 可选)– 新稀疏张量中包含的稀疏维数

例:

  1. >>> d = torch.tensor([[0, 0, 0], [9, 0, 10], [0, 0, 0]])
  2. >>> d
  3. tensor([[ 0, 0, 0],
  4. [ 9, 0, 10],
  5. [ 0, 0, 0]])
  6. >>> d.to_sparse()
  7. tensor(indices=tensor([[1, 1],
  8. [0, 2]]),
  9. values=tensor([ 9, 10]),
  10. size=(3, 3), nnz=2, layout=torch.sparse_coo)
  11. >>> d.to_sparse(1)
  12. tensor(indices=tensor([[1]]),
  13. values=tensor([[ 9, 0, 10]]),
  14. size=(3, 3), nnz=1, layout=torch.sparse_coo)

  1. trace() Tensor

参见 torch.trace()


  1. transpose(dim0, dim1) Tensor

参见 torch.transpose()


  1. transpose_(dim0, dim1) Tensor

就地版本的 transpose()


  1. triangular_solve(A, upper=True, transpose=False, unitriangular=False) -> (Tensor, Tensor)

参见 torch.triangular_solve()


  1. tril(k=0) Tensor

参见 torch.tril()


  1. tril_(k=0) Tensor

就地版本的 tril()


  1. triu(k=0) Tensor

参见 torch.triu()


  1. triu_(k=0) Tensor

就地版本的 triu()


  1. trunc() Tensor

参见 torch.trunc()


  1. trunc_() Tensor

就地版本的 trunc()


  1. type(dtype=None, non_blocking=False, **kwargs) str or Tensor

如果未提供dtype; ,则返回类型,否则将该对象强制转换为指定的类型。

如果它已经是正确的类型,则不执行任何复制,并返回原始对象。

参数

  • dtype (python:type 字符串)– 所需类型

  • non_blocking (bool ) – 如果True,并且源位于固定内存中,而目标位于 GPU 上,反之亦然,则相对于主机异步执行复制。 否则,该参数无效。

  • **kwargs – 为兼容起见,可以包含键async来代替non_blocking参数。 不推荐使用async arg。


  1. type_as(tensor) Tensor

将此张量转换为给定张量的类型。

如果张量已经是正确的类型,则这是无操作的。 相当于self.type(tensor.type())

参数

张量 (tensor)–具有所需类型的张量


  1. unbind(dim=0) seq

参见 torch.unbind()


  1. unfold(dimension, size, step) Tensor

返回一个张量,该张量包含self张量中尺寸为dimension的所有大小为 size 的切片。

两个切片之间的步长由step给出。

如果 sizedimself的尺寸dimension的大小,则返回张量中dimension的尺寸将是(sizeim-size)/step+ 1 。

在返回的张量中附加了尺寸为 size 的附加尺寸。

参数

  • dimension (python:int )–发生展开的尺寸

  • size (python:int )–展开的每个切片的大小

  • step (python:int )–每个切片之间的步骤

例:

  1. >>> x = torch.arange(1., 8)
  2. >>> x
  3. tensor([ 1., 2., 3., 4., 5., 6., 7.])
  4. >>> x.unfold(0, 2, 1)
  5. tensor([[ 1., 2.],
  6. [ 2., 3.],
  7. [ 3., 4.],
  8. [ 4., 5.],
  9. [ 5., 6.],
  10. [ 6., 7.]])
  11. >>> x.unfold(0, 2, 2)
  12. tensor([[ 1., 2.],
  13. [ 3., 4.],
  14. [ 5., 6.]])

  1. uniform_(from=0, to=1) Tensor

用从连续均匀分布中采样的数字填充self张量:

torch张量 - 图3


  1. unique(sorted=True, return_inverse=False, return_counts=False, dim=None)

返回输入张量的唯一元素。

参见 torch.unique()


  1. unique_consecutive(return_inverse=False, return_counts=False, dim=None)

从每个连续的等效元素组中除去除第一个元素外的所有元素。

参见 torch.unique_consecutive()


  1. unsqueeze(dim) Tensor

参见 torch.unsqueeze()


  1. unsqueeze_(dim) Tensor

就地版本的 unsqueeze()


  1. values() Tensor

如果self是稀疏的 COO 张量(即torch.sparse_coo布局),则返回包含值张量的视图。 否则,将引发错误。

另请参见 Tensor.indices()

注意

This method can only be called on a coalesced sparse tensor. See Tensor.coalesce() for details.


  1. var(dim=None, unbiased=True, keepdim=False) Tensor

参见 torch.var()


  1. view(*shape) Tensor

返回具有与self张量相同的数据但具有不同shape的新张量。

返回的张量共享相同的数据,并且必须具有相同数量的元素,但可能具有不同的大小。 要查看张量,新视图尺寸必须与其原始尺寸和步幅兼容,即每个新视图尺寸必须是原始尺寸的子空间,或者仅跨越满足以下条件的原始尺寸torch张量 - 图4 torch张量 - 图5的连续性状

torch张量 - 图6

否则,需要先调用 contiguous() 才能查看张量。 另请参见: reshape() ,如果形状兼容则返回一个视图,否则复制(相当于调用 contiguous())。

参数

形状(torch大小 python:int … )–所需大小

例:

  1. >>> x = torch.randn(4, 4)
  2. >>> x.size()
  3. torch.Size([4, 4])
  4. >>> y = x.view(16)
  5. >>> y.size()
  6. torch.Size([16])
  7. >>> z = x.view(-1, 8) # the size -1 is inferred from other dimensions
  8. >>> z.size()
  9. torch.Size([2, 8])
  10. >>> a = torch.randn(1, 2, 3, 4)
  11. >>> a.size()
  12. torch.Size([1, 2, 3, 4])
  13. >>> b = a.transpose(1, 2) # Swaps 2nd and 3rd dimension
  14. >>> b.size()
  15. torch.Size([1, 3, 2, 4])
  16. >>> c = a.view(1, 3, 2, 4) # Does not change tensor layout in memory
  17. >>> c.size()
  18. torch.Size([1, 3, 2, 4])
  19. >>> torch.equal(b, c)
  20. False

  1. view_as(other) Tensor

将此张量查看为与other相同的大小。 self.view_as(other)等效于self.view(other.size())

有关view的更多信息,请参见 view()

参数

other (torch.Tensor) – The result tensor has the same size as other.


  1. where(condition, y) Tensor

self.where(condition, y)等效于torch.where(condition, self, y)。 参见 torch.where()


  1. zero_() Tensor

用零填充self张量。


  1. class torch.BoolTensor

以下方法是 torch.BoolTensor 独有的。


  1. all()

  1. all() bool

如果张量中的所有元素均为 True,则返回 True,否则返回 False。

例:

  1. >>> a = torch.rand(1, 2).bool()
  2. >>> a
  3. tensor([[False, True]], dtype=torch.bool)
  4. >>> a.all()
  5. tensor(False, dtype=torch.bool)

  1. all(dim, keepdim=False, out=None) Tensor

如果张量的每一行中给定维度dim中的所有元素均为 True,则返回 True,否则返回 False。

如果keepdimTrue,则输出张量的大小与input相同,但尺寸为dim的大小为 1。否则,将压缩dim(请参见 torch.squeeze()),导致输出张量的尺寸比input小 1。

参数

  • dim (python:int ) – 缩小的尺寸

  • keepdim (bool ) – 输出张量是否保留dim

  • out (tensor 可选)– 输出的张量

例:

  1. >>> a = torch.rand(4, 2).bool()
  2. >>> a
  3. tensor([[True, True],
  4. [True, False],
  5. [True, True],
  6. [True, True]], dtype=torch.bool)
  7. >>> a.all(dim=1)
  8. tensor([ True, False, True, True], dtype=torch.bool)
  9. >>> a.all(dim=0)
  10. tensor([ True, False], dtype=torch.bool)

  1. any()

  1. any() bool

如果张量中的任何元素为 True,则返回 True,否则为 False。

例:

  1. >>> a = torch.rand(1, 2).bool()
  2. >>> a
  3. tensor([[False, True]], dtype=torch.bool)
  4. >>> a.any()
  5. tensor(True, dtype=torch.bool)

  1. any(dim, keepdim=False, out=None) Tensor

如果张量的每一行中给定维度dim中的任何元素为 True,则返回 True,否则为 False。

如果keepdimTrue,则输出张量的大小与input相同,但尺寸为dim的大小为 1。否则,将压缩dim(请参见 torch.squeeze()),导致输出张量的尺寸比input小 1。

参数

  • dim (python:int) – 缩小的尺寸

  • keepdim (bool) – 输出张量是否保留dim

  • out (Tensor, optional) – 输出的张量

例:

  1. >>> a = torch.randn(4, 2) < 0
  2. >>> a
  3. tensor([[ True, True],
  4. [False, True],
  5. [ True, True],
  6. [False, False]])
  7. >>> a.any(1)
  8. tensor([ True, True, True, False])
  9. >>> a.any(0)
  10. tensor([True, True])