初始化一个张量
- 直接从数据中初始化一个张量,数据类型会自动推导。
- 从numpy数组中初始化
- 从另一个张量中
torch.ones_like(x_data)
- 使用随机数或常量初始化
shape = (2, 3)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensors = torch.zeros(shape)
张量的属性
一个张量的属性有它的 shape, datatype, 和它被存储的地方device
tensor = torch.rand(3, 4)
print(f"Shape of tensor:{tensor.shape}")
print(f"Datatype of tensor:{tensor.dtype}")
print(f"Device tensor is stored on:{tensor.device}")
“”“”“”“
Shape of tensor:torch.Size([3, 4])
Datatype of tensor:torch.float32
Device tensor is stored on:cpu
对张量的操作
在torch库中有超过100中张量操作,每一种操作都能在GPU上运行。
默认来说张量是存在cpu上的,需要显示地将其移入GPU上,通过使用.to()方法,当然这需要在gpu可用的情况下。
if torch.cuda.is_available():
tensor = tensor.to('cuda')
torch.seed()
张量的数学运算
两个张量的矩阵相乘
t1 = tensor @ tensor.T
t2 = tensor.matmul(tensor.T)
t3 = torch.rand_like(tensor)
torch.matmul(tensor, tensor.T, out=t3)
两个矩阵的点积运算
z1 = tensor * tensor
z2 = tensor.mul(tensor)
z3 = torch.randlike(tensor)
torch.mul(tensor, tensor, out=z3)
in-place操作
将运算的结果存入操作数中叫做in-place操作,这种操作会在方法后面加一个下划线。比如x.copy_(), x.t_() 这样的操作将会改变x。
- in-place操作能够节省内存,但是在计算导数时可能会出现问题,因为会立即丢失历史记录,所以一般不鼓励这种操作。