torch.empty
torch.empty(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) → Tensor
'''
Returns a tensor filled with uninitialized data. The shape of the tensor is defined by the variable argument size.
Parameters
size (int...) – a sequence of integers defining the shape of the output tensor. Can be a variable number of arguments or a collection like a list or tuple.
out (Tensor, optional) – the output tensor.
dtype (torch.dtype, optional) – the desired data type of returned tensor. Default: if None, uses a global default (see torch.set_default_tensor_type()).
layout (torch.layout, optional) – the desired layout of returned Tensor. Default: torch.strided.
device (torch.device, optional) – the desired device of returned tensor. Default: if None, uses the current device for the default tensor type (see torch.set_default_tensor_type()). device will be the CPU for CPU tensor types and the current CUDA device for CUDA tensor types.
requires_grad (bool, optional) – If autograd should record operations on the returned tensor. Default: False.
pin_memory (bool, optional) – If set, returned tensor would be allocated in the pinned memory. Works only for CPU tensors. Default: False.
'''
参数说明
创建一个未被初始化数值的tensor,tensor的大小是由size确定
size: 定义tensor的shape ,这里可以是一个list 也可以是一个tuple
out: (可选)这里直接看后面这个 demo1例子吧,不太好描述
dtype:(可选)我不设置值 默认值就是torch.set_default_tensor_type制定的值,如果需要设置那就是torch.dtype的那几个。作用是指定返回tensor的数据类型
layout:(可选)值为 torch.layout。 torch.layout表示torch.Tensor内存布局的对象。有torch.strided(dense Tensors 默认)并为torch.sparse_coo(sparse COO Tensors)提供实验支持。
torch.strided代表密集张量,是最常用的内存布局。每个strided张量都会关联 一个torch.Storage,它保存着它的数据。这些张力提供了多维度, 存储的strided视图。Strides是一个整数型列表:k-th stride表示在张量的第k维从一个元素跳转到下一个元素所需的内存。关于这里的理解请看demo2
device:(可选)就是创建的tensor存放的device,这里就不做赘述了,大致概念了解看这里\
requires_grad: (可选)是bool 类型的值,默认值是False .因为 pytorch 后期的版本将Varibale 和Tensor进行合并了,这里的如果设置为Flase 表示再反响传播的时候不会对这个节点机型求导,如果你对tensorflow熟悉,
requires_grad (bool, optional) – If autograd should record operations on the returned tensor. Default: False.
例子
demo1
y=torch.tensor([[1,2,3]])
print(y) # 这里的输出的y的是 tensor([[1, 2, 3]])
z=torch.empty(size=[1,3],out=y)
print(z) # 这里输出的z和上一步输出的一模一样
demo2
x=torch.empty([2,5])
x.stride()
'''
输出分别为:
tensor([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
(5, 1) #注意看这里
'''
y=x.t()
y.stride()
'''
输出分别为:
tensor([[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.]])
(1, 5) #注意看这里
'''