torch常用操作

1、torch的属性

假设y是tensor类型张量

方法作用示例
is_tensor张量是tensor类型返回Truetorch.is_tensor(y)
numel返回输入张量元素的总数y.numel()
shape返回输入张量的形状y.size()
size返回输入张量的形状y.shape
dtype返回输入张量元素的类型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.T
take将张量展平,取出对应索引的张量组成新的张量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 dimension
maxReturns 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.
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值