Tensors

初始化一个 tensor

x_data = torch.tensor(list_data)
x_np = torch.from_numpy(np_array)
# retains the properties of x_data
x_ones = torch.ones_like(x_data, dtype=None)
# overrides the datatype of x_data
x_rand = torch.rand_like(x_data, dtype=torch.float) 

shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)
torch.randn((), device=device, dtype=dtype)
torch.full((), 0.3, device=device, dtype=dtype, requires_grad=True)
  1. list
  2. np.array
  3. 从一个 tensor,使其形状一样
  4. ones_like:全一
  5. rand_like:随机
  6. dtype:更改数据类型或者一样
  7. shape
  8. shape 可以是一个 integer 或者 tuple 或者 list

tensor 的属性

  1. shape
  2. dtype
  3. device

操作

if torch.cuda.is_available():
    tensor = tensor.to("cuda")

tensor = torch.ones(4, 4)
print(f"First row: {tensor[0]}")
print(f"First column: {tensor[:, 0]}")
print(f"Last column: {tensor[..., -1]}")

t1 = torch.cat([tensor, tensor, tensor], dim=1)
  1. to:转移 device 以及可以转换 dtype。

    By default, tensors are created on the CPU. Keep in mind that copying large tensors across devices can be expensive in terms of time and memory!

  2. 索引:可修改的

    注意 ... 表示省略并包含全部

  3. Join tensors

    1. cat:不改变维度个数,在指定的维度进行合并
    2. stack:在指定的合并维度增加一个维度排列