目录
new_tensor(data, dtype=None, device=None, requires_grad=False) → Tensor
new_full(size, fill_value, dtype=None, device=None, requires_grad=False) → Tensor
new_empty(size, dtype=None, device=None, requires_grad=False) → Tensor
new_ones(size, dtype=None, device=None, requires_grad=False) → Tensor
new_zeros(size, dtype=None, device=None, requires_grad=False) → Tensor
add_(value=1, other) -> Tensor
addbmm(beta=1, alpha=1, batch1, batch2) → Tensor
addbmm_(beta=1, alpha=1, batch1, batch2) → Tensor
addcdiv(value=1, tensor1, tensor2) → Tensor
addcdiv_(value=1, tensor1, tensor2) → Tensor
addcmul(value=1, tensor1, tensor2) → Tensor
addcmul_(value=1, tensor1, tensor2) → Tensor
addmm(beta=1, alpha=1, mat1, mat2) → Tensor
addmm_(beta=1, alpha=1, mat1, mat2) → Tensor
addmv(beta=1, alpha=1, mat, vec) → Tensor
addmv_(beta=1, alpha=1, mat, vec) → Tensor
addr(beta=1, alpha=1, vec1, vec2) → Tensor
addr_(beta=1, alpha=1, vec1, vec2) → Tensor
allclose(other, rtol=1e-05, atol=1e-08, equal_nan=False) → Tensor
argmax(dim=None, keepdim=False) → LongTensor
argmin(dim=None, keepdim=False) → LongTensor
argsort(dim=-1, descending=False) → LongTensor
as_strided(size, stride, storage_offset=0) → Tensor
backward(gradient=None, retain_graph=None, create_graph=False)[source]
baddbmm(beta=1, alpha=1, batch1, batch2) → Tensor
baddbmm_(beta=1, alpha=1, batch1, batch2) → Tensor
bernoulli(*, generator=None) → Tensor
bernoulli_(p=0.5, *, generator=None) → Tensor
bernoulli_(p_tensor, *, generator=None) → Tensor
bincount(weights=None, minlength=0) → Tensor
cauchy_(median=0, sigma=1, *, generator=None) → Tensor
cholesky(upper=False) → Tensor
cholesky_inverse(upper=False) → Tensor
cholesky_solve(input2, upper=False) → Tensor
chunk(chunks, dim=0) → List of Tensors
copy_(src, non_blocking=False) → Tensor
cuda(device=None, non_blocking=False) → Tensor
cumprod(dim, dtype=None) → Tensor
cumsum(dim, dtype=None) → Tensor
diag_embed(offset=0, dim1=-2, dim2=-1) → Tensor
diagonal(offset=0, dim1=0, dim2=1) → Tensor
fill_diagonal_(fill_value, wrap=False) → Tensor
eig(eigenvectors=False) -> (Tensor, Tensor)
exponential_(lambd=1, *, generator=None) → Tensor
fft(signal_ndim, normalized=False) → Tensor
flatten(input, start_dim=0, end_dim=-1) → Tensor
geometric_(p, *, generator=None) → Tensor
get_device() -> Device ordinal (Integer)
hardshrink(lambd=0.5) → Tensor
histc(bins=100, min=0, max=0) → Tensor
ifft(signal_ndim, normalized=False) → Tensor
index_add_(dim, index, tensor) → Tensor
index_add(dim, index, tensor) → Tensor
index_copy_(dim, index, tensor) → Tensor
index_copy(dim, index, tensor) → Tensor
index_fill_(dim, index, val) → Tensor
index_fill(dim, index, value) → Tensor
index_put_(indices, value, accumulate=False) → Tensor
index_put(indices, value, accumulate=False) → Tensor
index_select(dim, index) → Tensor
irfft(signal_ndim, normalized=False, onesided=True, signal_sizes=None) → Tensor
kthvalue(k, dim=None, keepdim=False) -> (Tensor, LongTensor)
log_normal_(mean=1, std=2, *, generator=None)
logsumexp(dim, keepdim=False) → Tensor
lu(pivot=True, get_infos=False)[source]
lu_solve(LU_data, LU_pivots) → Tensor
masked_scatter(mask, tensor) → Tensor
masked_fill(mask, value) → Tensor
max(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor)
mean(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor)
median(dim=None, keepdim=False) -> (Tensor, LongTensor)
min(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor)
mode(dim=None, keepdim=False) -> (Tensor, LongTensor)
multinomial(num_samples, replacement=False, *, generator=None) → Tensor
narrow(dimension, start, length) → Tensor
narrow_copy(dimension, start, length) → Tensor
norm(p='fro', dim=None, keepdim=False, dtype=None)[source]
normal_(mean=0, std=1, *, generator=None) → Tensor
ormqr(input2, input3, left=True, transpose=False) → Tensor
prod(dim=None, keepdim=False, dtype=None) → Tensor
put_(indices, tensor, accumulate=False) → Tensor
qr(some=True) -> (Tensor, Tensor)
random_(from=0, to=None, *, generator=None) → Tensor
renorm(p, dim, maxnorm) → Tensor
renorm_(p, dim, maxnorm) → Tensor
repeat_interleave(repeats, dim=None) → Tensor
requires_grad_(requires_grad=True) → Tensor
rfft(signal_ndim, normalized=False, onesided=True) → Tensor
scatter(dim, index, source) → Tensor
scatter_(dim, index, src) → Tensor
scatter_add_(dim, index, other) → Tensor
scatter_add(dim, index, source) → Tensor
set_(source=None, storage_offset=0, size=None, stride=None) → Tensor
sort(dim=-1, descending=False) -> (Tensor, LongTensor)
split(split_size, dim=0)[source]
sparse_mask(input, mask) → Tensor
std(dim=None, unbiased=True, keepdim=False) → Tensor
sum(dim=None, keepdim=False, dtype=None) → Tensor
svd(some=True, compute_uv=True) -> (Tensor, Tensor, Tensor)
symeig(eigenvectors=False, upper=True) -> (Tensor, Tensor)
to(dtype, non_blocking=False, copy=False) → Tensor
to(device=None, dtype=None, non_blocking=False, copy=False) → Tensor
to(other, non_blocking=False, copy=False) → Tensor
topk(k, dim=None, largest=True, sorted=True) -> (Tensor, LongTensor)
to_sparse(sparseDims) → Tensor
transpose(dim0, dim1) → Tensor
transpose_(dim0, dim1) → Tensor
triangular_solve(A, upper=True, transpose=False, unitriangular=False) -> (Tensor, Tensor)
type(dtype=None, non_blocking=False, **kwargs) → str or Tensor
unfold(dimension, size, step) → Tensor
uniform_(from=0, to=1) → Tensor
unique(sorted=True, return_inverse=False, return_counts=False, dim=None)[source]
unique_consecutive(return_inverse=False, return_counts=False, dim=None)[source]
var(dim=None, unbiased=True, keepdim=False) → Tensor
all(dim, keepdim=False, out=None) → Tensor
any(dim, keepdim=False, out=None) → Tensor
torch.Tensor是一个包含单一数据类型元素的多维矩阵。Torch定义了9种CPU张量类型和9种GPU张量类型:
| Data type | dtype | CPU tensor | GPU tensor |
|---|---|---|---|
| 32-bit floating point |
|
|
|
| 64-bit floating point |
|
|
|
| 16-bit floating point |
|
|
|
| 8-bit integer (unsigned) |
|
|
|
| 8-bit integer (signed) |
|
|
|
| 16-bit integer (signed) |
|
|
|
| 32-bit integer (signed) |
|
|
|
| 64-bit integer (signed) |
|
|
|
| Boolean |
|
|
torch.Tensor是默认张量类型的别名(torch.FloatTensor)。张量可以使用torch.tensor()构造函数从Python列表或序列中构造:
- >>> torch.tensor([[1., -1.], [1., -1.]])
- tensor([[ 1.0000, -1.0000],
- [ 1.0000, -1.0000]])
- >>> torch.tensor(np.array([[1, 2, 3], [4, 5, 6]]))
- tensor([[ 1, 2, 3],
- [ 4, 5, 6]])
警告:
通常复制数据,如果你有一个张量数据并且仅仅想改变它的requires_grad标记,使用requires_grad_()或detach()来避免复制。如果你有一个numpy数组并且想避免复制,使用torch.as_tensor()。指定数据类型的张量可以通过torch.dtype或者torch.device来构建或者张量创建op来构建。
- >>> torch.zeros([2, 4], dtype=torch.int32)
- tensor([[ 0, 0, 0, 0],
- [ 0, 0, 0, 0]], dtype=torch.int32)
- >>> cuda0 = torch.device('cuda:0')
- >>> torch.ones([2, 4], dtype=torch.float64, device=cuda0)
- tensor([[ 1.0000, 1.0000, 1.0000, 1.0000],
- [ 1.0000, 1.0000, 1.0000, 1.0000]], dtype=torch.float64, device='cuda:0')
张量的内容可以通过Python的检索或者切片符号来访问和构建:
- >>> x = torch.tensor([[1, 2, 3], [4, 5, 6]])
- >>> print(x[1][2])
- tensor(6)
- >>> x[0][1] = 8
- >>> print(x)
- tensor([[ 1, 8, 3],
- [ 4, 5, 6]])
使用torch.Tensor.item()从包含单个值的张量中获得Python数值:
- >>> x = torch.tensor([[1]])
- >>> x
- tensor([[ 1]])
- >>> x.item()
- 1
- >>> x = torch.tensor(2.5)
- >>> x
- tensor(2.5000)
- >>> x.item()
- 2.5
张量可以用requires_grad=True来创建,这样torch.autograd记录对它们的操作,以便自动微分。
- >>> x = torch.tensor([[1., -1.], [1., 1.]], requires_grad=True)
- >>> out = x.pow(2).sum()
- >>> out.backward()
- >>> x.grad
- tensor([[ 2.0000, -2.0000],
- [ 2.0000, 2.0000]])
每个张量都和torch.Storage相关,这保持了一个数据。张量类提供了一个多维,存储的条带视图,并定义其上的数值操作。
注意:
改变张量的方法用下划线后缀标记。例如,torch.FloatTensor.abs_()计算当前的绝对值并返回修改后的张量,而torch.FloatTensor.abs()计算结果得到一个新的张量。
注意:
为了改变已经存在的torch.device或者torch.dtype,考虑使用张量上的to()方法。
警告:
目前实施的torch.Tensor引入了内存开销,因此在有很多小张量的应用中可能会导致意外的高内存使用量。如果是这样,可以考虑使用一个大型结构。
torch.TensorThere are a few main ways to create a tensor, depending on your use case.
有几种主要的方式来创建一个张量,取决于你使用的情况:
创建一个指定大小的张量,使用torch.* 张量创建op。torch.*_like张量创建op(Creation Ops)。创建一个和其他张量具有相同类型但是尺寸不同的张量,使用tensor.new_*操作ops。new_tensor(data, dtype=None, device=None, requires_grad=False) → Tensor以数据作为张量数据返回一个新的张量。默认情况下,返回的张量数据和这个张量的torch.dtype和torch.device相同。
警告:
new_tensor()通常复制这个数据。如果你有一个张量数据并且想避免复制,使用torch.Tensor.requires_grad_()或torch.Tensor.detach()。如果你有numpy数据并且想避免复制,使用torch.from_numpy()。
警告:
当数据是一个张量x,new_tensor()从它所传递的内容中读出“数据”,并且构造叶变量。因此,tensor.new_tensor(x)和x.clone()相等,并且tensor.new_tensor(x, requires_grad=True)和x.clone().detach().requires_grad_(True)相等。同推荐使用clone()和detach()。
参数:
data (array_like) – The returned Tensor copies data. 返回的张量复制数据data。
dtype (torch.dtype, optional) – 返回数期望的类型。默认情况下:和这个张量的torch.dtype相同。
device (torch.device, optional) – 返回张量期望的设备。默认:如果没有的话,和这个张量相同。
requires_grad (bool, optional) – 在返回的张量上如果autograd是推荐的,默认:Fasle
例:
- >>> tensor = torch.ones((2,), dtype=torch.int8)
- >>> data = [[0, 1], [2, 3]]
- >>> tensor.new_tensor(data)
- tensor([[ 0, 1],
- [ 2, 3]], dtype=torch.int8)
new_full(size, fill_value, dtype=None, device=None, requires_grad=False) → Tensor返回一个size的张量,size用fill_value填充。默认情况下,返回张量和这个张量的torch.dtype和torch.device相等。
参数:
fill_value (scalar) – 填充输出张量的数。
dtype (torch.dtype, optional) – 返回张量的期望type。默认:如果没有的话,和这个张量的torch.dtype相同。
device (torch.device, optional) – 返回张量的期望设备,默认:如果没有的话,和这个张量的torch.device相同。
requires_grad (bool, optional) – 在返回张量上autograd是否应该推荐操作。默认:False。
例:
- >>> tensor = torch.ones((2,), dtype=torch.float64)
- >>> tensor.new_full((3, 4), 3.141592)
- tensor([[ 3.1416, 3.1416, 3.1416, 3.1416],
- [ 3.1416, 3.1416, 3.1416, 3.1416],
- [ 3.1416, 3.1416, 3.1416, 3.1416]], dtype=torch.float64)
new_empty(size, dtype=None, device=None, requires_grad=False) → Tensor返回一个size的张量,size用未初始化的数据填充。默认情况下,返回的张量和这个张量具有相同的torch.dtype和torch.device。
参数:
dtype (torch.dtype, optional) – 返回张量的期望类型。默认:如果没有的话,和这个张量的torch.dtype相同。
device (torch.device, optional) – 返回张量期望的设备。默认:和这个张量的torch.device相同。
requires_grad (bool, optional) – 再返回的张量上autograd是否应该记录操作,默认:False。
例:
- >>> tensor = torch.ones(())
- >>> tensor.new_empty((2, 3))
- tensor([[ 5.8182e-18, 4.5765e-41, -1.0545e+30],
- [ 3.0949e-41, 4.4842e-44, 0.0000e+00]])
new_ones(size, dtype=None, device=None, requires_grad=False) → Tensor返回size的张量,size用1填充。默认情况下,返回的张量和这个张量具有相同的torch.dtype和torch.device。
参数:
fill_value (scalar) – 填充输出张量的数。
dtype (torch.dtype, optional) – 返回张量的期望type。默认:如果没有的话,和这个张量的torch.dtype相同。
device (torch.device, optional) – 返回张量的期望设备,默认:如果没有的话,和这个张量的torch.device相同。
requires_grad (bool, optional) – 在返回张量上autograd是否应该推荐操作。默认:False。
例:
- >>> tensor = torch.tensor((), dtype=torch.int32)
- >>> tensor.new_ones((2, 3))
- tensor([[ 1, 1, 1],
- [ 1, 1, 1]], dtype=torch.int32)
new_zeros(size, dtype=None, device=None, requires_grad=False) → Tensor返回size的张量,size用0填充。默认情况下,返回的张量和这个张量具有相同的torch.dtype和torch.device。
参数:
fill_value (scalar) – 填充输出张量的数。
dtype (torch.dtype, optional) – 返回张量的期望type。默认:如果没有的话,和这个张量的torch.dtype相同。
device (torch.device, optional) – 返回张量的期望设备,默认:如果没有的话,和这个张量的torch.device相同。
requires_grad (bool, optional) – 在返回张量上autograd是否应该推荐操作。默认:False。
Example:
- >>> tensor = torch.tensor((), dtype=torch.float64)
- >>> tensor.new_zeros((2, 3))
- tensor([[ 0., 0., 0.],
- [ 0., 0., 0.]], dtype=torch.float64)
is_cuda如果张量存储在GPU上的话就为真,否则为假。
devicegrad默认情况下,属性为none,在第一次调用backward()为self计算梯度时成为一个张量。然后,该属性将包含计算得到的梯度,对backward()的未来调用将在其中累积(添加)梯度。
ndimT维度转置后的张量。
如果n是x中的维度数,x.T等于x.permute(n-1, n-2, ..., 0)
abs() → Tensorabs_() → Tensoracos() → Tensoracos_() → Tensoracos()的原地版本
add(value) → Tensoradd(value=1, other) -> Tensor
add_(value) → Tensoraddbmm(beta=1, alpha=1, batch1, batch2) → Tensoraddbmm_(beta=1, alpha=1, batch1, batch2) → Tensoraddcdiv(value=1, tensor1, tensor2) → Tensoraddcdiv_(value=1, tensor1, tensor2) → Tensoraddcmul(value=1, tensor1, tensor2) → Tensoraddcmul_(value=1, tensor1, tensor2) → Tensoraddmm(beta=1, alpha=1, mat1, mat2) → Tensoraddmm_(beta=1, alpha=1, mat1, mat2) → Tensoraddmm()的原地版本
addmv(beta=1, alpha=1, mat, vec) → Tensoraddmv_(beta=1, alpha=1, mat, vec) → Tensoraddmv()的原地版本
addr(beta=1, alpha=1, vec1, vec2) → Tensoraddr_(beta=1, alpha=1, vec1, vec2) → Tensorallclose(other, rtol=1e-05, atol=1e-08, equal_nan=False) → Tensorapply_(callable) → Tensor在张量中对每个元素使用函数callable(),用callable返回的值替换每个元素。
注意:
这个函数仅仅在CPU中使用,并且不应该在需要高性能的代码章节中使用。
argmax(dim=None, keepdim=False) → LongTensorargmin(dim=None, keepdim=False) → LongTensorargsort(dim=-1, descending=False) → LongTensor查看函数torch.argsort
asin() → Tensorasin_() → Tensoras_strided(size, stride, storage_offset=0) → Tensoratan() → Tensoratan2(other) → Tensoratan2_(other) → Tensoratan_() → Tensorbackward(gradient=None, retain_graph=None, create_graph=False)[source]计算当前张量关于图等级的梯度。图用链式法则求导。如果张量是一个非标量(例如,它的数据超过了一个)并且需要梯度,函数需要额外指定梯度。应该是一个匹配类型和位置的张量,包含关于self的微分函数的梯度。函数在叶中累积梯度-你也许需要在调用它之间置零。
参数:
gradient (Tensor or None) – 关于张量的梯度。如果它是一个张量,它将自动转换成不需要梯度的张量,除非create_graph为真。对标量张量不能指定任何值或者不需要梯度的张量。如果需要接受空值,这个参数是可选的。
retain_graph (bool, optional) – 如果为假,用来计算梯度的的图将被释放。请注意,在几乎所有情况下,不需要将此选项设置为True,而且通常可以以一种更有效的方式进行处理。默认值为create_graph。
create_graph (bool, optional) – 如果为真,则构造导数图,允许计算高阶导数。默认值为False。
baddbmm(beta=1, alpha=1, batch1, batch2) → Tensorbaddbmm_(beta=1, alpha=1, batch1, batch2) → Tensorbernoulli(*, generator=None) → Tensor返回一个张量,其中每个result[i]从Bernoulli(self[i])。self必须为浮点数类型,结果具有相同的dtype。查看torch.bernoulli()
bernoulli_(p=0.5, *, generator=None) → Tensor将self的每个位置用Bernoulli(p)独立的采样填充。self可以是积分的dtype。
bernoulli_(p_tensor, *, generator=None) → Tensorp_tensor应该是一个包含概率的张量,用来产生二进制的随机数。self的
个元素必须设置成Bernoulli(p_tensor[i])的采样值。self可以有dtype, 但是p_tensor必须有浮点数的dtype。也看bernoulli() 看torch.bernoulli()。
bfloat16() → Tensorself.bfloat16()和self.to(torch.bfloat16)相等,查看to()。
bincount(weights=None, minlength=0) → Tensorbitwise_not() → Tensorbitwise_not_() → Tensorbmm(batch2) → Tensorbool() → Tensorself.bool()和self.to(torch.bool)相等,查看to()
byte() → Tensorself.byte()和self.to(torch.uint8)相等, 查看to()
cauchy_(median=0, sigma=1, *, generator=None) → Tensor将张量用柯西分布得到的数填充:

ceil() → Tensorceil_() → Tensorchar() → Tensorself.char()和self.to(torch.int8)相等,查看to()
cholesky(upper=False) → Tensorcholesky_inverse(upper=False) → Tensorcholesky_solve(input2, upper=False) → Tensorchunk(chunks, dim=0) → List of Tensorsclamp(min, max) → Tensorclamp_(min, max) → Tensorclamp()的原地版本
clone() → Tensor返回self张量的拷贝,拷贝具有和self相同的尺寸和数据类型。
注意:
不像copy_(),这个函数在计算图中推荐。传播到克隆张量上的梯度将会传播到原始张量上。
contiguous() → TensorReturns a contiguous tensor containing the same data as self tensor. If self tensor is contiguous, this function returns the self tensor.
返回包含和self数据相同数据的原始张量。如果self张量是连续的,这个函数返回self张量。
copy_(src, non_blocking=False) → TensorCopies the elements from src into self tensor and returns self.
从src复制元素到self张量,并且返回self。src张量必须和self张量可广播。它可以是不同的数据类型或驻留在不同的设备上。
参数:
cos() → Tensorcos_() → Tensorcosh() → Tensorcosh_() → Tensorcpu() → TensorReturns a copy of this object in CPU memory.
在CPU内存中返回这个对象的复制。如果目标已经在CPU内存中存在,就不执行复制,并且返回原始对象。
cross(other, dim=-1) → Tensorcuda(device=None, non_blocking=False) → Tensor在CUDA内存中返回这个对象的复制。如果这个对象已经在CUDA内存中存在,并且不在当前的设备上,不进行复制并且返回原始对象。
参数:
device (torch.device) – 目标GPU设备,默认是目前的GPU设备。
non_blocking (bool) – 如果为真,并且在CPU和GPU之间复制,复制关于host是异步的。对其他情况,这个参数无效。
cumprod(dim, dtype=None) → Tensorcumsum(dim, dtype=None) → Tensordata_ptr() → intReturns the address of the first element of self tensor.
返回self张量的第一个元素的地址。
dequantize() → TensorGiven a quantized Tensor, dequantize it and return the dequantized float Tensor.
给定一个量化的张量,反量化它并且返回翻两化的浮点张量。
det() → Tensordense_dim() → int如果self是一个稀疏COO张量(即torch.sparse_coo布局),这将返回密集维数。否则,将抛出一个错误,
也可以查看Tensor.sparse_dim()。
detach()返回一个从目前计算图分离的新张量,结果永远不需要梯度。
注意:
返回和原始张量共享相同存储的张量。它们中的任何一个上的就地修改都将被看到,并且可能在正确性检查中触发错误。重要通知:以前,对返回的张量的大小/ stride / storage更改(如resize_ / resize_as_ / set_ / transpose_)也会更新原始张量。现在,这些原地的变化不会再更新原来的张量,反而会引发一个错误。对于稀疏张量:对返回的张量的索引/值的改变(如zero_ / copy_ / add_)将不再更新原来的张量,而是会触发一个错误。
detach_()Detaches the Tensor from the graph that created it, making it a leaf. Views cannot be detached in-place.
从图中分离一个张量并创建它,将它作为一个叶子。视图不能在适当的位置分离。
diag(diagonal=0) → Tensordiag_embed(offset=0, dim1=-2, dim2=-1) → Tensordiagflat(offset=0) → Tensordiagonal(offset=0, dim1=0, dim2=1) → Tensorfill_diagonal_(fill_value, wrap=False) → Tensor填满至少是二维张量的主对角线。当dims>为2时,输入的所有尺寸必须是相等的长度。这个函数修改输入张量的位置,并返回输入张量。
参数:
fill_value (Scalar) – 填充值
wrap (bool) – 对于高矩阵,在N列之后的对角“包裹”。
例:
- >>> a = torch.zeros(3, 3)
- >>> a.fill_diagonal_(5)
- tensor([[5., 0., 0.],
- [0., 5., 0.],
- [0., 0., 5.]])
- >>> b = torch.zeros(7, 3)
- >>> b.fill_diagonal_(5)
- tensor([[5., 0., 0.],
- [0., 5., 0.],
- [0., 0., 5.],
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.]])
- >>> c = torch.zeros(7, 3)
- >>> c.fill_diagonal_(5, wrap=True)
- tensor([[5., 0., 0.],
- [0., 5., 0.],
- [0., 0., 5.],
- [0., 0., 0.],
- [5., 0., 0.],
- [0., 5., 0.],
- [0., 0., 5.]])
digamma() → Tensordigamma_() → Tensordim() → int返回self张量的维度数。
dist(other, p=2) → Tensordiv(value) → Tensordiv_(value) → Tensordot(tensor2) → Tensordouble() → Tensorself.double()和self.to(torch.float64)相等,查看to()。
eig(eigenvectors=False) -> (Tensor, Tensor)element_size() → int返回单个元素的大小,以字节为单位。
例:
- >>> torch.tensor([]).element_size()
- 4
- >>> torch.tensor([], dtype=torch.uint8).element_size()
- 1
eq(other) → Tensoreq_(other) → Tensorequal(other) → boolerf() → Tensorerf_() → Tensorerfc() → Tensorerfc_() → Tensorerfinv() → Tensorerfinv_() → Tensorexp() → Tensorexp_() → Tensorexpm1() → Tensorexpm1_() → Tensorexpand(*sizes) → Tensor返回扩展为更大尺寸的单维自张量的新视图。将-1作为维度的大小传递意味着不改变该维度的大小。张量也可以扩展到更大的维数,新的维数将被附加在前面。对于新的维度,大小不能设置为-1。扩展一个张量不会分配新的内存,而只会在现有张量上创建一个新视图,其中通过将stride设置为0,将size为1的维度扩展为更大的尺寸。大小1的任何维度都可以扩展为任意值,而不需要分配新的内存。
参数:
警告:
展开张量的多个元素可以指单个存储单元。因此,就地操作(特别是向量化的操作)可能会导致不正确的行为。如果你需要写张量,请先克隆它们。
例:
- >>> x = torch.tensor([[1], [2], [3]])
- >>> x.size()
- torch.Size([3, 1])
- >>> x.expand(3, 4)
- tensor([[ 1, 1, 1, 1],
- [ 2, 2, 2, 2],
- [ 3, 3, 3, 3]])
- >>> x.expand(-1, 4) # -1 means not changing the size of that dimension
- tensor([[ 1, 1, 1, 1],
- [ 2, 2, 2, 2],
- [ 3, 3, 3, 3]])
expand_as(other) → Tensor将这个张量展开到与其他张量相同的大小。self.expand_as(other)等同于self.expand(other.size())。有关expand的更多信息,请参见expand()。
参数:
exponential_(lambd=1, *, generator=None) → Tensor用指数分布的元素填充self张量:

fft(signal_ndim, normalized=False) → Tensorfill_(value) → Tensor用指定的值填充自张量。
flatten(input, start_dim=0, end_dim=-1) → Tensorflip(dims) → Tensorfloat() → Tensorself.float()等价于self.to(torch.float32),查看to()。
floor() → Tensorfloor_() → Tensorfmod(divisor) → Tensorfmod_(divisor) → Tensorfrac() → Tensorfrac_() → Tensorgather(dim, index) → Tensorge(other) → Tensorge_(other) → Tensorgels(A)[source]geometric_(p, *, generator=None) → TensorFills self tensor with elements drawn from the geometric distribution:
用几何分布产生的元素来填充张量:

geqrf() -> (Tensor, Tensor)ger(vec2) → Tensorget_device() -> Device ordinal (Integer)对于CUDA张量,这个函数返回张量所在的GPU的序号。对于CPU张量,抛出一个错误。
例:
- >>> x = torch.randn(3, 4, 5, device='cuda:0')
- >>> x.get_device()
- 0
- >>> x.cpu().get_device() # RuntimeError: get_device is not implemented for type torch.FloatTensor
gt(other) → Tensorgt_(other) → Tensorhalf() → Tensorself.half()和self.to(torch.float16)相等, 查看to().
hardshrink(lambd=0.5) → Tensor查看torch.nn.functional.hardshrink()
histc(bins=100, min=0, max=0) → Tensorifft(signal_ndim, normalized=False) → Tensorindex_add_(dim, index, tensor) → Tensor将张量的元素按指标给出的顺序加到指标上,累加到self张量中。例如dim == 0, index[i] == j,则将张量的第i行加到self的第j行。张量的第dim维数必须与索引的长度相同(索引的长度必须是一个向量),并且所有其他维数必须与self匹配,否则会产生错误。
注意:
当使用CUDA后端时,此操作可能会导致不确定的行为,而不容易关闭。请参阅关于后台重现性的说明。
参数:
例:
- >>> x = torch.ones(5, 3)
- >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float)
- >>> index = torch.tensor([0, 4, 2])
- >>> x.index_add_(0, index, t)
- tensor([[ 2., 3., 4.],
- [ 1., 1., 1.],
- [ 8., 9., 10.],
- [ 1., 1., 1.],
- [ 5., 6., 7.]])
index_add(dim, index, tensor) → Tensortorch.Tensor.index_add_()的原地版本
index_copy_(dim, index, tensor) → Tensor将张量的元素按指标给出的顺序加到指标上,累加到self张量中。例如dim == 0, index[i] == j,则将张量的第i行加到self的第j行。张量的第dim维数必须与索引的长度相同(索引的长度必须是一个向量),并且所有其他维数必须与self匹配,否则会产生错误。
参数:
例:
- >>> x = torch.zeros(5, 3)
- >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float)
- >>> index = torch.tensor([0, 4, 2])
- >>> x.index_copy_(0, index, t)
- tensor([[ 1., 2., 3.],
- [ 0., 0., 0.],
- [ 7., 8., 9.],
- [ 0., 0., 0.],
- [ 4., 5., 6.]])
index_copy(dim, index, tensor) → Tensortorch.tensor.index_copy_().tensor1对应于self张量中的torch.Tensor.index_copy_()。
index_fill_(dim, index, val) → Tensor用val值填充自张量的元素,按索引中给出的顺序选择索引。
参数:
dim (int) – dimension along which to index
index (LongTensor) – indices of self tensor to fill in
val (float) – the value to fill with
例:
- >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float)
- >>> index = torch.tensor([0, 2])
- >>> x.index_fill_(1, index, -1)
- tensor([[-1., 2., -1.],
- [-1., 5., -1.],
- [-1., 8., -1.]])
index_fill(dim, index, value) → Tensortorch.Tensor.index_fill_()的错误版本。
index_put_(indices, value, accumulate=False) → Tensor使用指标中指定的指标(即张量的元组)将值从张量值放入到张量本身中。张量的表达式。tensor.index_put_(indices, value)等于tensor[indices] = value。返回self。如果累加为真,张量中的元素被加到self中。如果accumulate为False,如果索引包含重复元素,则行为未定义。
参数:
index_put(indices, value, accumulate=False) → Tensorindex_select(dim, index) → Tensorindices() → TensorIf self is a sparse COO tensor (i.e., with torch.sparse_coo layout), this returns a view of the contained indices tensor. Otherwise, this throws an error.
如果self是一个稀疏COO张量(即torch.sparse_coo布局),这将返回包含索引张量的视图。否则,将抛出一个错误。也查看Tensor.values()。
注意:
这种方法只能在聚结稀疏张量上调用。详细信息请参见tenables .coalesce()。
int() → Tensorself.int()等价于self.to(torch.int32)。查看to()。
int_repr() → Tensor给定一个量化张量,self.int_repr()返回一个CPU张量,它以uint8_t作为数据类型,存储给定张量的底层uint8_t值。
inverse() → Tensorirfft(signal_ndim, normalized=False, onesided=True, signal_sizes=None) → Tensoris_contiguous() → bool
如果自张量在内存中以C顺序连续,则返回True。
is_floating_point() → bool如果self的数据类型是浮点数据类型,则返回True。
is_leaf()所有requires_grad为假的张量按照约定都是叶张量。对于requires_grad为真的张量,它们将是叶张量如果它们是由用户创建的。这意味着它们不是操作的结果,因此grad_fn是None。只有叶张量将在调用backward()期间填充它们的grad。要为非叶张量填充grad,可以使用retain_grad()。
例:
- >>> a = torch.rand(10, requires_grad=True)
- >>> a.is_leaf
- True
- >>> b = torch.rand(10, requires_grad=True).cuda()
- >>> b.is_leaf
- False
- # b was created by the operation that cast a cpu Tensor into a cuda Tensor
- >>> c = torch.rand(10, requires_grad=True) + 2
- >>> c.is_leaf
- False
- # c was created by the addition operation
- >>> d = torch.rand(10).cuda()
- >>> d.is_leaf
- True
- # d does not require gradients and so has no operation creating it (that is tracked by the autograd engine)
- >>> e = torch.rand(10).cuda().requires_grad_()
- >>> e.is_leaf
- True
- # e requires gradients and has no operations creating it
- >>> f = torch.rand(10, requires_grad=True, device="cuda")
- >>> f.is_leaf
- True
- # f requires grad, has no operation creating it
is_pinned()[source]如果该张量存储在固定内存中,则返回true
is_set_to(tensor) → bool如果该对象从Torch C API中引用与给定张量相同的THTensor对象,则返回True。
is_shared()[source]检查张量是否在共享内存中。这对于CUDA张量总是成立的。
is_signed() → bool如果self的数据类型是有符号数据类型,则返回True。
is_sparse()item() → number返回这个张量的值作为标准Python值。这只适用于只有一个元素的张量。其他情况请参见tolist()。这个操作是不可微的。
例:
- >>> x = torch.tensor([1.0])
- >>> x.item()
- 1.0
kthvalue(k, dim=None, keepdim=False) -> (Tensor, LongTensor)le(other) → Tensorle_(other) → Tensorlerp(end, weight) → Tensorlerp_(end, weight) → Tensorlog() → Tensorlog_() → Tensorlogdet() → Tensorlog10() → Tensorlog10_() → Tensorlog1p() → Tensorlog1p_() → Tensorlog2() → Tensorlog2_() → Tensorlog_normal_(mean=1, std=2, *, generator=None)将self张量用给定均值和标准差的对数正太分布中采样的数来填充。注意mean和std分别是基本正太分布的均值和标准差,不是返回的分布:

logsumexp(dim, keepdim=False) → Tensorlong() → Tensorself.long()和self.to(torch.int64)相等. 查看to().
lstsq(A) -> (Tensor, Tensor)lt(other) → Tensorlt_(other) → Tensorlu(pivot=True, get_infos=False)[source]lu_solve(LU_data, LU_pivots) → Tensormap_(tensor, callable)对self张量中的每个袁术适应callable,并且给定张量和存储self张量中的结果。self张量和给定张量必须是可以广播的。callable应该有签名:
def callable(a, b) -> number
masked_scatter_(mask, source)当source所处的位置为true的话,将source张量元素复制到self张量。mask的姓张必须和基本张量的形状是可广播的。source中元素的数量应该至少与mask中的元素数量相同。
参数:
mask (BoolTensor) – boolen掩膜
source (Tensor) – 复制的张量
注意:
self张量上的掩膜操作,不是在源张量上。
masked_scatter(mask, tensor) → Tensortorch.Tensor.masked_scatter_()的错误版本
masked_fill_(mask, value)如果mask所处的位置为真的话,将self张量的元素进行填充。mask的形状必须和基本张量形状是可广播的。
参数:
mask (BoolTensor) – 布尔mask
value (float) – 要填充的值
masked_fill(mask, value) → Tensortorch.Tensor.masked_fill_()的错误版本
masked_select(mask) → Tensormatmul(tensor2) → Tensormatrix_power(n) → Tensormax(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor)mean(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor)median(dim=None, keepdim=False) -> (Tensor, LongTensor)min(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor)mm(mat2) → Tensormode(dim=None, keepdim=False) -> (Tensor, LongTensor)mul(value) → Tensormul_(value)multinomial(num_samples, replacement=False, *, generator=None) → Tensormv(vec) → Tensormvlgamma(p) → Tensormvlgamma_(p) → Tensornarrow(dimension, start, length) → Tensor例:
- >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
- >>> x.narrow(0, 0, 2)
- tensor([[ 1, 2, 3],
- [ 4, 5, 6]])
- >>> x.narrow(1, 1, 2)
- tensor([[ 2, 3],
- [ 5, 6],
- [ 8, 9]])
narrow_copy(dimension, start, length) → Tensor与string .narrow()相同,只是返回一个副本而不是共享存储。这主要是针对稀疏张量,它没有共享存储的狭窄方法。调用' narrow_copy 和' dimemsion > self.sparse_dim() '将返回一个相关稠密维数缩小的副本,以及' self '。形状的相应更新。
ndimension() → intne(other) → Tensorne_(other) → Tensorneg() → Tensorneg_() → Tensornelement() → intnonzero() → LongTensornorm(p='fro', dim=None, keepdim=False, dtype=None)[source]normal_(mean=0, std=1, *, generator=None) → Tensor将自张量填入由mean和std参数化的正态分布的元素样本。
numel() → intnumpy() → numpy.ndarray返回self张量作为Numpy ndarry。这个张量和返回的ndarray共享相同的底层存储。自张量的变化会反映在ndarray上,反之亦然。
orgqr(input2) → Tensorormqr(input2, input3, left=True, transpose=False) → Tensorpermute(*dims) → Tensor返回这个张量的维度。
参数:
例:
- >>> x = torch.randn(2, 3, 5)
- >>> x.size()
- torch.Size([2, 3, 5])
- >>> x.permute(2, 0, 1).size()
- torch.Size([5, 2, 3])
pin_memory() → Tensor复制张量到固定的内存(如果它还没有固定)。
pinverse() → Tensorpow(exponent) → Tensorpow_(exponent) → Tensorprod(dim=None, keepdim=False, dtype=None) → Tensorput_(indices, tensor, accumulate=False) → Tensor将张量中的元素复制到指标指定的位置。为了建立索引,自张量被当作一维张量处理。如果累加为真,张量中的元素被加到self中。如果accumulate为False,如果索引包含重复元素,则行为未定义。
参数:
例:
- >>> src = torch.tensor([[4, 3, 5],
- [6, 7, 8]])
- >>> src.put_(torch.tensor([1, 3]), torch.tensor([9, 10]))
- tensor([[ 4, 9, 5],
- [ 10, 7, 8]])
qr(some=True) -> (Tensor, Tensor)qscheme() → torch.qscheme返回给定q张量的量化方案。
q_scale() → float给定一个被线性(仿射)量化的张量,返回底层quantizer()的尺度。
q_zero_point() → int给定一个被线性(仿射)量化的张量,返回底层quantizer()的zero_point 。
random_(from=0, to=None, *, generator=None) → Tensor将张量用在[from, to-1]的离散归一化分得到的数字分布进行填充。如果没有指定,这些值通常只受自张量数据类型的限制。但是,对于浮点类型,如果未指定,范围将是[0,2^mantissa],以确保每个值都是可表示的。例如,torch.tensor(1,dtype=torch.double).random_()在[0,2^53]中将是均匀的。
reciprocal() → Tensorreciprocal_() → Tensorregister_hook(hook)[source]注册一个反传的hook。每当计算一个相对于张量的梯度时,就会调用这个hook。hook应该有以下签名:
hook(grad) -> Tensor or None
hook不应该修改它的参数,但是它可以选择返回一个新的梯度,它将用来代替grad。这个函数返回一个句柄,该句柄带有一个方法handle.remove(),该方法从模块中删除hook 。
例:
- >>> v = torch.tensor([0., 0., 0.], requires_grad=True)
- >>> h = v.register_hook(lambda grad: grad * 2) # double the gradient
- >>> v.backward(torch.tensor([1., 2., 3.]))
- >>> v.grad
-
- 2
- 4
- 6
- [torch.FloatTensor of size (3,)]
-
- >>> h.remove() # removes the hook
remainder(divisor) → Tensorremainder_(divisor) → Tensorrenorm(p, dim, maxnorm) → Tensorrenorm_(p, dim, maxnorm) → Tensorrepeat(*sizes) → Tensor沿着指定的维度复制张量。不像expand(),这个函数复制张量的数据。
警告:
troch.repeat()的行为与numpy不同。重复,但更类似于numpy.tile。对于类似于numpy的操作符。重复,请参阅torch.repeat_interleave ()。
参数:
例:
- >>> x = torch.tensor([1, 2, 3])
- >>> x.repeat(4, 2)
- tensor([[ 1, 2, 3, 1, 2, 3],
- [ 1, 2, 3, 1, 2, 3],
- [ 1, 2, 3, 1, 2, 3],
- [ 1, 2, 3, 1, 2, 3]])
- >>> x.repeat(4, 2, 1).size()
- torch.Size([4, 2, 3])
repeat_interleave(repeats, dim=None) → Tensorrequires_grad()如果需要计算这个张量的梯度,则为真,否则为假。
注意:
需要为一个张量计算梯度的事实并不意味着将填充grad属性,更多细节请参见is_leaf。
requires_grad_(requires_grad=True) → Tensor如果autograd应该记录对这个张量的操作,请更改:在适当的位置设置这个张量的requires_grad属性。require_grad_()的主要用例是告诉autograd开始记录一个张量张量上的操作。如果张量有requires_grad=False(因为它是通过DataLoader获得的,或者需要预处理或初始化),那么tenast .requires_grad_()使得autograd将开始记录对张量的操作。
参数:
True.例:
- >>> # Let's say we want to preprocess some saved weights and use
- >>> # the result as new weights.
- >>> saved_weights = [0.1, 0.2, 0.3, 0.25]
- >>> loaded_weights = torch.tensor(saved_weights)
- >>> weights = preprocess(loaded_weights) # some function
- >>> weights
- tensor([-0.5503, 0.4926, -2.1158, -0.8303])
-
- >>> # Now, start to record operations done to weights
- >>> weights.requires_grad_()
- >>> out = weights.pow(2).sum()
- >>> out.backward()
- >>> weights.grad
- tensor([-1.1007, 0.9853, -4.2316, -1.6606])
reshape(*shape) → Tensor返回与self具有相同数据和元素数量但具有指定形状的张量。如果形状与当前形状兼容,此方法将返回一个视图。查看手troch. tensor .view()何时可以返回视图。
参数:
reshape_as(other) → Tensor将这个张量返回为另一个张量的相同形状。self. rempe_as (other)等同于self. rempe_other .sizes())。如果other.sizes()与当前形状兼容,此方法将返回一个视图。查看手torch.tensor.view()何时可以返回视图。有关reshape的更多信息,请参见reshape()。
参数:
other (torch.Tensor) – 结果张量与其他张量具有相同的形状。
resize_(*sizes) → Tensor调整self张量到指定的大小。如果元素的数量大于当前存储的大小,那么底层存储将调整大小以适应新的元素数量。如果元素的数量较小,则不更改底层存储。保留现有的元素,但未初始化任何新内存。
警告:
这是一个低级方法。存储被重新解释为C-contiguous,忽略当前的步长(除非目标大小等于当前大小,在这种情况下张量保持不变)。在大多数情况下,你会希望使用view(),它检查连续性,或者使用reshape(),它在需要时复制数据。若要使用自定义大步就地更改大小,请参见set_()。
参数:
例:
- >>> x = torch.tensor([[1, 2], [3, 4], [5, 6]])
- >>> x.resize_(2, 2)
- tensor([[ 1, 2],
- [ 3, 4]])
resize_as_(tensor) → Tensor将self张量调整为与指定张量相同的大小。这相当于self.resize_(tensor.size())。
retain_grad()[source]为非叶张量启用.grad属性。
rfft(signal_ndim, normalized=False, onesided=True) → Tensorroll(shifts, dims) → Tensorrot90(k, dims) → Tensorround() → Tensorround_() → Tensorrsqrt() → Tensorrsqrt_() → Tensorscatter(dim, index, source) → Tensorscatter_(dim, index, src) → Tensor将所有的值从张量src写入到自己的指标张量中。对于src中的每个值,其输出索引由其在src中的索引(dimension != dim)和在索引(index For dimension = dim)中对应的值来指定。
- self[index[i][j][k]][j][k] = src[i][j][k] # if dim == 0
- self[i][index[i][j][k]][k] = src[i][j][k] # if dim == 1
- self[i][j][index[i][j][k]] = src[i][j][k] # if dim == 2
gather()期望操作的相反操作。self, index和src(如果是一个张量的话)应该有相同的维度。对所哟维度d,也需要使得index.size(d) <= src.size(d),对所有d != dim,是index.size(d) <= self.size(d)。此外,对于gather(), index的值必须在0和self.size(dim) - 1之间,并且沿着指定维度dim的一行中的所有值必须是唯一的。
参数:
dim (int) – 索引所沿的轴
index (LongTensor) – 元素的索引可以是空的,也可以是和src一样大小的。当为空时,操作返回identity
src (Tensor) – 要分散的源元素,incase值没有指定
value (float) – 在src没有指定的情况下,要分散的源元素
例:
- >>> x = torch.rand(2, 5)
- >>> x
- tensor([[ 0.3992, 0.2908, 0.9044, 0.4850, 0.6004],
- [ 0.5735, 0.9006, 0.6797, 0.4152, 0.1732]])
- >>> torch.zeros(3, 5).scatter_(0, torch.tensor([[0, 1, 2, 0, 0], [2, 0, 0, 1, 2]]), x)
- tensor([[ 0.3992, 0.9006, 0.6797, 0.4850, 0.6004],
- [ 0.0000, 0.2908, 0.0000, 0.4152, 0.0000],
- [ 0.5735, 0.0000, 0.9044, 0.0000, 0.1732]])
-
- >>> z = torch.zeros(2, 4).scatter_(1, torch.tensor([[2], [3]]), 1.23)
- >>> z
- tensor([[ 0.0000, 0.0000, 1.2300, 0.0000],
- [ 0.0000, 0.0000, 0.0000, 1.2300]])
scatter_add_(dim, index, other) → Tensor以类似scatter_()的方式,在指标张量中指定的指标处将从另一个张量的所有值加到自己。对于other中的每个值,将其添加到self中的一个索引中,该索引由other中的index != dim和index,对dimension = dim指定。对于一个三维张量,将self更新为:
- self[index[i][j][k]][j][k] += other[i][j][k] # if dim == 0
- self[i][index[i][j][k]][k] += other[i][j][k] # if dim == 1
- self[i][j][index[i][j][k]] += other[i][j][k] # if dim == 2
self,index和其他应该有相同的维数。也要求index.size (d) < = other.size所有维d (d),而且index.size (d) < = self.size (d)为所有维d ! = dim.Moreover,至于收集(),索引的值必须介于0和self.size(dim)- 1包容,和所有的值在一行指定的维度的必须是唯一的。
注意:
当使用CUDA后端时,此操作可能会导致不确定的行为,而不容易关闭。请参阅关于后台重现性的说明。
参数:
dim (int) – 索引所沿的轴
index (LongTensor) – 散布和添加元素的索引可以是空的,也可以是与src相同大小的。当为空时,操作返回identity。
other (Tensor) – the source elements to scatter and add
例:
- >>> x = torch.rand(2, 5)
- >>> x
- tensor([[0.7404, 0.0427, 0.6480, 0.3806, 0.8328],
- [0.7953, 0.2009, 0.9154, 0.6782, 0.9620]])
- >>> torch.ones(3, 5).scatter_add_(0, torch.tensor([[0, 1, 2, 0, 0], [2, 0, 0, 1, 2]]), x)
- tensor([[1.7404, 1.2009, 1.9154, 1.3806, 1.8328],
- [1.0000, 1.0427, 1.0000, 1.6782, 1.0000],
- [1.7953, 1.0000, 1.6480, 1.0000, 1.9620]])
scatter_add(dim, index, source) → Tensortorch.Tensor.scatter_add_()的错误版本
select(dim, index) → Tensor在给定的指标上沿着选定的维数对自张量进行切片。这个函数返回的张量去掉了给定的维数。
参数:
注意:
select()相当于切片。例如,张量。select(0, index)等于张量[index]和张量。select(2, index)等价于张量[:,:,index]。
set_(source=None, storage_offset=0, size=None, stride=None) → Tensor设置基础的存储、尺寸和不符。如果source是张量的话,self张量将会共享相同的存储,并且和source具有相同的尺寸和步幅。一个张量中元素的变化将反映在另一个张量中。如果源是一个存储,则该方法设置底层存储、偏移量、大小和跨越。
参数:
source (Tensor or Storage) – 使用的张量或存储
storage_offset (int, optional) – 存储中的偏移量
size (torch.Size, optional) – 所需的大小。默认为源文件的大小。
stride (tuple, optional) – 所需的步伐。默认为C - continuous跨步。
share_memory_()[source]将底层存储移动到共享内存。如果底层存储已经在共享内存中,对于CUDA张量,这是一个no-op。共享内存中的张量不能调整大小。
short() → Tensorself.short()等self.to(torch.int16),看to().
sigmoid() → Tensorsigmoid_() → Tensorsign() → Tensorsign_() → Tensorsin() → Tensorsin_() → Tensorsinh() → Tensorsinh_() → Tensorsize() → torch.SizeReturns the size of the self tensor. The returned value is a subclass of tuple.
Example:
- >>> torch.empty(3, 4, 5).size()
- torch.Size([3, 4, 5])
slogdet() -> (Tensor, Tensor)See torch.slogdet()
solve(A) → Tensor, TensorSee torch.solve()
sort(dim=-1, descending=False) -> (Tensor, LongTensor)See torch.sort()
split(split_size, dim=0)[source]See torch.split()
sparse_mask(input, mask) → TensorReturns a new SparseTensor with values from Tensor input filtered by indices of mask and values are ignored. input and mask must have the same shape.
Parameters
input (Tensor) – an input Tensor
mask (SparseTensor) – a SparseTensor which we filter input based on its indices
例:
- >>> nnz = 5
- >>> dims = [5, 5, 2, 2]
- >>> I = torch.cat([torch.randint(0, dims[0], size=(nnz,)),
- torch.randint(0, dims[1], size=(nnz,))], 0).reshape(2, nnz)
- >>> V = torch.randn(nnz, dims[2], dims[3])
- >>> size = torch.Size(dims)
- >>> S = torch.sparse_coo_tensor(I, V, size).coalesce()
- >>> D = torch.randn(dims)
- >>> D.sparse_mask(S)
- tensor(indices=tensor([[0, 0, 0, 2],
- [0, 1, 4, 3]]),
- values=tensor([[[ 1.6550, 0.2397],
- [-0.1611, -0.0779]],
-
- [[ 0.2326, -1.0558],
- [ 1.4711, 1.9678]],
-
- [[-0.5138, -0.0411],
- [ 1.9417, 0.5158]],
-
- [[ 0.0793, 0.0036],
- [-0.2569, -0.1055]]]),
- size=(5, 5, 2, 2), nnz=4, layout=torch.sparse_coo)
sparse_dim() → int如果self是一个稀疏COO张量(即torch.sparse_coo布局),这将返回稀疏维数。否则,将抛出一个错误。参见Tensor.dense_dim ()。
sqrt() → Tensorsqrt_() → Tensorsqueeze(dim=None) → TensorSee torch.squeeze()
squeeze_(dim=None) → Tensorstd(dim=None, unbiased=True, keepdim=False) → Tensorstft(n_fft, hop_length=None, win_length=None, window=None, center=True, pad_mode='reflect', normalized=False, onesided=True)[source]警告:
这个函数在0.4.1版本中修改了签名。使用前面的签名调用可能会导致错误或返回不正确的结果。
storage() → torch.Storage返回底层存储。
storage_offset() → int返回自张量在底层存储中的偏移量,该偏移量以存储元素的数量(而不是字节)表示。
例:
- >>> x = torch.tensor([1, 2, 3, 4, 5])
- >>> x.storage_offset()
- 0
- >>> x[3:].storage_offset()
- 3
storage_type() → type返回底层存储的类型。
stride(dim) → tuple or int返回自张量的步长。Stride是在指定维度dim中从一个元素跳到下一个元素所必需的跳跃。如果没有传入参数,则返回所有大步的元组。否则,将返回一个整数值作为特定维度dim中的stride。
参数:
例:
- >>> x = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
- >>> x.stride()
- (5, 1)
- >>>x.stride(0)
- 5
- >>> x.stride(-1)
- 1
sub(value, other) → Tensor从自张量中减去一个标量或张量。如果同时指定了value和other,则other的每个元素在使用前都按值缩放。当other是一个张量时,other的形状必须与下面的张量的形状可广播。
sub_(x) → Tensorsum(dim=None, keepdim=False, dtype=None) → Tensorsum_to_size(*size) → Tensor把这个张量的大小相加。大小必须是可广播到这个张量大小。
参数:
svd(some=True, compute_uv=True) -> (Tensor, Tensor, Tensor)symeig(eigenvectors=False, upper=True) -> (Tensor, Tensor)t() → Tensort_() → Tensorto(*args, **kwargs) → Tensor执行张量dtype和/或设备转换。一个torch.dtype和torch.device是从self的参数中推断出来的。(* args, * * kwargs)。
注意:
如果自张量已经有了正确的torch.dtype和torch.device,然后返回self。否则,返回的张量是具有所需torch.dtype和torch.device的副本。以下是打电话给你的方法。
to(dtype, non_blocking=False, copy=False) → Tensor返回具有指定dtype的张量
to(device=None, dtype=None, non_blocking=False, copy=False) → Tensor返回具有指定device和(可选)dtype的张量。如果dtype为None,则推断为self.dtype。当非阻塞时,尽可能尝试与主机进行异步转换,例如,将固定内存的CPU张量转换为CUDA张量。当复制被设置,一个新的张量被创建,即使张量已经匹配所需的转换。
to(other, non_blocking=False, copy=False) → Tensor用相同的火炬返回一个torch.dtype型和torch.device作为其他张量。当非阻塞时,尽可能尝试与主机进行异步转换,例如,将固定内存的CPU张量转换为CUDA张量。当复制被设置,一个新的张量被创建,即使张量已经匹配所需的转换。
例:
- >>> tensor = torch.randn(2, 2) # Initially dtype=float32, device=cpu
- >>> tensor.to(torch.float64)
- tensor([[-0.5044, 0.0005],
- [ 0.3310, -0.0584]], dtype=torch.float64)
-
- >>> cuda0 = torch.device('cuda:0')
- >>> tensor.to(cuda0)
- tensor([[-0.5044, 0.0005],
- [ 0.3310, -0.0584]], device='cuda:0')
-
- >>> tensor.to(cuda0, dtype=torch.float64)
- tensor([[-0.5044, 0.0005],
- [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0')
-
- >>> other = torch.randn((), dtype=torch.float64, device=cuda0)
- >>> tensor.to(other, non_blocking=True)
- tensor([[-0.5044, 0.0005],
- [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0')
to_mkldnn() → Tensor返回torch中张量的布局。
take(indices) → Tensortan() → Tensortan_() → Tensortanh() → Tensortanh_() → Tensortolist()” tolist() -> 数字列表
以(嵌套的)列表的形式返回张量。对于标量,返回一个标准的Python数字,就像item()一样。如果有必要,张量会首先自动移动到CPU。这个操作是不可微的。
例:
- >>> a = torch.randn(2, 2)
- >>> a.tolist()
- [[0.012766935862600803, 0.5415473580360413],
- [-0.08909505605697632, 0.7729271650314331]]
- >>> a[0,0].tolist()
- 0.012766935862600803
topk(k, dim=None, largest=True, sorted=True) -> (Tensor, LongTensor)to_sparse(sparseDims) → Tensor返回张量的稀疏副本。PyTorch支持坐标格式的稀疏张量。
参数:
例:
- >>> d = torch.tensor([[0, 0, 0], [9, 0, 10], [0, 0, 0]])
- >>> d
- tensor([[ 0, 0, 0],
- [ 9, 0, 10],
- [ 0, 0, 0]])
- >>> d.to_sparse()
- tensor(indices=tensor([[1, 1],
- [0, 2]]),
- values=tensor([ 9, 10]),
- size=(3, 3), nnz=2, layout=torch.sparse_coo)
- >>> d.to_sparse(1)
- tensor(indices=tensor([[1]]),
- values=tensor([[ 9, 0, 10]]),
- size=(3, 3), nnz=1, layout=torch.sparse_coo)
trace() → Tensortranspose(dim0, dim1) → Tensortranspose_(dim0, dim1) → Tensortriangular_solve(A, upper=True, transpose=False, unitriangular=False) -> (Tensor, Tensor)tril(k=0) → Tensortril_(k=0) → Tensortriu(k=0) → Tensortriu_(k=0) → Tensortrunc() → Tensortrunc_() → Tensortype(dtype=None, non_blocking=False, **kwargs) → str or Tensor如果没有提供dtype,则返回类型,否则将此对象强制转换为指定的类型。如果已经是正确的类型,则不执行复制并返回原始对象。
参数:
dtype (type or string) – 期望的类型
non_blocking (bool) – 如果为真,并且源在固定的内存中,而目标在GPU上,反之亦然,那么复制就会相对于主机异步执行。否则,该参数将无效。
**kwargs – 为了兼容性,可以用关键异步代替非阻塞参数。不赞成使用异步参数。
type_as(tensor) → Tensor将此张量转换为给定张量的类型。如果张量已经是正确的类型,这就是一个no-op。它等价于self.type(tensor.type())
参数:
unbind(dim=0) → sequnfold(dimension, size, step) → Tensor返回一个张量,该张量包含维数中自张量大小的所有片。两个切片之间的步骤是一步一步给出的。如果sizedim是self的维度维度的大小,那么返回张量中维度维度的大小为(sizedim - size) / step + 1。返回张量中附加了一个尺寸大小的附加维数。
参数:
例:
- >>> x = torch.arange(1., 8)
- >>> x
- tensor([ 1., 2., 3., 4., 5., 6., 7.])
- >>> x.unfold(0, 2, 1)
- tensor([[ 1., 2.],
- [ 2., 3.],
- [ 3., 4.],
- [ 4., 5.],
- [ 5., 6.],
- [ 6., 7.]])
- >>> x.unfold(0, 2, 2)
- tensor([[ 1., 2.],
- [ 3., 4.],
- [ 5., 6.]])
uniform_(from=0, to=1) → Tensor用连续均匀分布抽样的数填充self张量:

unique(sorted=True, return_inverse=False, return_counts=False, dim=None)[source]返回输入张量的唯一元素。
unique_consecutive(return_inverse=False, return_counts=False, dim=None)[source]从每个连续的等价元素组中消除除第一个元素以外的所有元素。
unsqueeze(dim) → Tensorunsqueeze_(dim) → Tensorvalues() → Tensor如果self是一个稀疏COO张量(即 torch.sparse_coo布局),这将返回包含值张量的视图。否则,将抛出一个错误。参见Tensor.indices ()。
注意:
这种方法只能在聚结稀疏张量上调用。详细信息请参见tenables .coalesce()。
var(dim=None, unbiased=True, keepdim=False) → Tensorview(*shape) → Tensor返回的张量共享相同的数据,必须有相同数量的元素,但可能有不同的大小。对于一个被观察的张量,新的观察尺寸必须与它原来的尺寸和步幅相匹配。,每个新的视图维数必须要么是原始维数的子空间,要么只张成原始维数d d+1,…d+k,它满足下面的近似条件,对任意i = 0,...,k-1:

否则,需要在查看张量之前调用contiguous())。参见:reshape(),如果形状兼容,它将返回一个视图,否则将返回副本(相当于调用邻接())。
参数:
例:
- >>> x = torch.randn(4, 4)
- >>> x.size()
- torch.Size([4, 4])
- >>> y = x.view(16)
- >>> y.size()
- torch.Size([16])
- >>> z = x.view(-1, 8) # the size -1 is inferred from other dimensions
- >>> z.size()
- torch.Size([2, 8])
-
- >>> a = torch.randn(1, 2, 3, 4)
- >>> a.size()
- torch.Size([1, 2, 3, 4])
- >>> b = a.transpose(1, 2) # Swaps 2nd and 3rd dimension
- >>> b.size()
- torch.Size([1, 3, 2, 4])
- >>> c = a.view(1, 3, 2, 4) # Does not change tensor layout in memory
- >>> c.size()
- torch.Size([1, 3, 2, 4])
- >>> torch.equal(b, c)
- False
view_as(other) → Tensor把这个张量和其他张量的大小一样。self.view_as(other)等同于self.view(other.size())。有关view的更多信息,请参见view()。
参数:
where(condition, y) → Tensorself.where(condition, y) 等于torch.where(condition, self, y),查看torch.where()
zero_() → Tensor用0填充self张量。
torch.BoolTensor下面的方法对torch.BoolTensor来讲是独特的。
all()all() → bool如果张量中的所有元素都为真,则返回真,否则返回假。
例:
- >>> a = torch.rand(1, 2).bool()
- >>> a
- tensor([[False, True]], dtype=torch.bool)
- >>> a.all()
- tensor(False, dtype=torch.bool)
all(dim, keepdim=False, out=None) → Tensor如果给定维数dim中张量的每一行中的所有元素都为真,则返回真,否则返回假。如果keepdim为真,则输出张量的大小与输入张量的大小相同,只是在dim维度中,它的大小为1。否则,dim会被压缩(参见torch.squeeze()),导致输出张量比输入张量少1维。
参数:
例:
- >>> a = torch.rand(4, 2).bool()
- >>> a
- tensor([[True, True],
- [True, False],
- [True, True],
- [True, True]], dtype=torch.bool)
- >>> a.all(dim=1)
- tensor([ True, False, True, True], dtype=torch.bool)
- >>> a.all(dim=0)
- tensor([ True, False], dtype=torch.bool)
any()
any() → bool如果张量中的任何元素为真,则返回真,否则返回假。
例:
- >>> a = torch.rand(1, 2).bool()
- >>> a
- tensor([[False, True]], dtype=torch.bool)
- >>> a.any()
- tensor(True, dtype=torch.bool)
any(dim, keepdim=False, out=None) → Tensor如果给定维数dim中张量的每一行中的任何元素为真,则返回真,否则返回假。如果keepdim为真,则输出张量的大小与输入张量的大小相同,只是在dim维度中,它的大小为1。否则,dim会被压缩(参见torch.squeeze()),导致输出张量比输入张量少1维。
参数:
例:
- >>> a = torch.randn(4, 2) < 0
- >>> a
- tensor([[ True, True],
- [False, True],
- [ True, True],
- [False, False]])
- >>> a.any(1)
- tensor([ True, True, True, False])
- >>> a.any(0)
- tensor([True, True])