1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 # PyTorch 张量基础 ## 张量简介 张量是一种特殊的数据结构,与数组和矩阵非常相似。在PyTorch中,我们使用张量对模型的输入和输出以及模型的参数进行编码。 ## 基本操作 ### 创建张量 ```python import torch import numpy as np # 从随机数据和全1数据创建张量 shape = (2, 3) rand_tensor = torch.rand(shape) # 随机张量 ones_tensor = torch.ones(shape) # 全1张量
张量属性 1 2 3 print (f"Shape of tensor: {rand_tensor.shape} " ) print (f"Datatype of tensor: {rand_tensor.dtype} " ) print (f"Device tensor is stored on: {rand_tensor.device} " )
索引和切片 1 2 tensor = torch.ones(4 , 4 ) tensor[:, 1 ] = 0
张量连接 1 t1 = torch.cat([tensor, tensor, tensor], dim=1 )
张量运算 元素级乘法 1 2 3 print (tensor.mul(tensor)) print (tensor * tensor)
矩阵乘法 1 2 3 print (tensor.matmul(tensor.T)) print (tensor @ tensor.T)
原地操作(In-place)
注意:原地操作可以节省内存,但在计算导数时可能会出现问题,因此不鼓励使用。
与NumPy互转 张量转NumPy数组 1 2 t = torch.ones(5 ) n = t.numpy()
NumPy数组转张量 1 2 n = np.ones(5 ) t = torch.from_numpy(n)