Tensors是一种特殊的数据结构,类似于数组和矩阵。在Pytorch,用tensors去给模型的输入和输出,以及模型的参数编码。
Tensors与Numpy的ndarrays相似,除了能运行在GPUs或者其他硬件加速器上。Tensors也针对自动微分进行优化。
import torch import numpy as np
初始化Tensor
初始化Tensor有多种方式。
直接从数据
data=[[1,2],[3,4]] x_data=torch.tensor(data) print(x_data)
numpy array
np_array=np.array(data) x_np=torch.from_numpy(np_array) print(x_np)
另外一个tensor
新的tensor还保留旧tensor的属性(shape,datatype),除非明确地覆盖它。
x_ones=torch.ones_like(x_data) # retain the properties of x_data print(f'Ones Tensor: \n {x_ones}\n') x_rand=torch.rand_like(x_data,dtype=torch.float) # overrides the datatype of x_data print(f'Random Tensor:\n {x_rand} \n')
随机或常量数据
shape=(2,3,) rand_tensor=torch.rand(shape) ones_tensor=torch.ones(shape) zeros_tensor=torch.zeros(shape) print(f'Random Tensor:\n {rand_tensor} \n') print(f'Ones Tensor:\n {ones_tensor} \n') print(f'Zeros Tensor:\n {zeros_tensor} \n')
Tensor属性
tensor=torch.rand(3,4) print(f'Shape of tensor:{tensor.shape}') # shape print(f'Datatype of tensor:{tensor.dtype}') # dtype print(f'Device of tensor:{tensor.device}') # device
操作Tensors
超过100中tensor操作,包括科学计算,线性回归,矩阵操作(转置,索引,切片),采样等。而这些操作都是运行在GPU上的。
tensors默认是在CPU创建运行上的,但是可以明确调用.to方法(确认有GPU)指定移动到GPU运行。记住复制大量tensors就时间和内存是非常代价高的。
# we move our tensor to the GPU if available if torch.cuda.is_available(): tensor=tensor.to('cuda') print(tensor)
标准numpy-like 索引和切片
tensor=torch.ones(4,4) print(f'First low:{tensor[0]}') print(f'First column:{tensor[:,0]}') print(f'Last column:{tensor[...,-1]}') tensor[:,1]=0 print(tensor)
连接tensor
t1=torch.cat([tensor,tensor,tensor],dim=1) print(t1)
算术操作
# This computes the matrix multiplication between two tensors. y1,y2,y3 will have the same value # tensor.T returns the transpose of a tensor y1=tensor @ tensor.T y2=tensor.matmul(tensor.T) y3=torch.rand_like(y1) torch.matmul(tensor,tensor.T,out=y3) # This computes the element-wise product. z1,z2,z3 will have the same value. z1=tensor*tensor z2=tensor.mul(tensor) z3=torch.rand_like(tensor) torch.mul(tensor,tensor,out=z3)
单元素tensor
单元素tensor可以进行聚合运算。可以通过.item()函数转换成数字值。
agg=tensor.sum() agg_item=agg.item() print(agg_item,type(agg_item))
In-place 操作
操作的结果直接保存到操作数。方法由后缀_表示。
print(f'{tensor}\n') tensor.add_(5) print(tensor)
In-place操作可以节省一些内存,但在计算导数时可能会出现问题,因为会立即丢失历史记录。因此,不鼓励使用它们。
桥接NumPy
在CPU上的Tensors与Numpy数组共享底层内存,改变一个也会改变另一个。
Tensor转Numpy数组
t=torch.ones(5) print(f't:{t}') n=t.numpy() print(f'n:{n}')
改变tensor会影响Numpy数组
t.add_(1) print(f't:{t}') print(f'n:{n}')
Numpy数组转Tensor
n=np.ones(5)
t=torch.from_numpy(n)
改变Numpy数组影响tensor
np.add(n,1,out=n) print(f't:{t}') print(f'n:{n}')
posted on
浙公网安备 33010602011771号