栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

torch常用操作

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

torch常用操作

torch常用操作 1、torch的属性2、创建torch的操作(⭐为最常用)3、torch的变换操作4、torch的随机数生成5、torch的数学操作6、torch的梯度操作7、torch的取值操作

1、torch的属性

假设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.
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/266798.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号