假设y是tensor类型张量
方法作用示例is_tensor张量是tensor类型返回Truetorch.is_tensor(y)numel返回输入张量元素的总数y.numel()shape返回输入张量的形状y.size()size返回输入张量的形状y.shapedtype返回输入张量元素的类型y.dtype 2、创建torch的操作(⭐为最常用) 方法作用示例⭐tensor用输入数据创建张量(同np的array方法)torch.tensor([[1,2],[3,4]])as_tensor将数据转变为张量torch.as_tensor(x)from_numpy从numpy.ndarray类型创建张量torch.from_numpy(x)⭐zeros返回全0张量 形状为参数torch.zeros(3,4)zeros_like返回和输入形状一样的全0张量torch.zeros_like(x.shape)⭐ones返回全1张量 形状为参数torch.ones(3,4)ones_like返回和输入形状一样的全1张量torch.ones_like(x.shape)⭐arange生成数值为范围内数的张量torch.arange(12).reshape(3,4)range类似arangetorch.range(0,12,2)linspace生成一维张量 从strat到end均分为step份torch.linspace(0,12,10)eye生成主对角线都是1的张量矩阵torch.eye(4,4) 3、torch的变换操作 方法作用示例cat在规定维度上连接两个张量torch.cat((x,y),dim 0)reshape重塑张量形状x.reshape(3,4)T转置x.Ttake将张量展平 取出对应索引的张量组成新的张量torch.take(y,torch.tensor([0,1]))item将张量转换为标量(类似asscalar)x.item() 4、torch的随机数生成 方法作用示例normal正态分布torch.normal(mean 0,std 1,size (3,4))randn标准正态分布torch.randn(size (3,4))randint随机整数torch.randint(0,12,size (3,4))rand0-1上均匀分布torch.rand(size (3,4)) 5、torch的数学操作 方法作用示例abs各元素绝对值torch.tensor([[1,2],[3,4]])exp各元素指数torch.as_tensor(x)log各元素log2torch.from_numpy(x)log10各元素log10单元格 6、torch的梯度操作张量是否保留梯度信息由torch.no_grad(), torch.enable_grad(), and torch.set_grad_enabled()等决定.
1、在梯度计算前要有保存梯度的地方
#mxnet x.attach_grad() #pytorch x.requires_grad_(True)
2、计算y
#mxnet with autograd.record(): y net(x) y.backward() #pytorch y net(x)
梯度信息此时已保留在x.grad中
7、torch的取值操作通过指定axis 0 可以让其在维度0上进行相应操作
方法作用argmaxReturns the indices of the maximum value of all elements in the input tensor.argminReturns the indices of the minimum value(s) of the flattened tensor or along a dimensionmaxReturns the maximum value of all elements in the input tensor.meanReturns the mean value of all elements in the input tensor.normReturns the matrix norm or vector norm of a given tensor.sumReturns the sum of all elements in the input tensor.


