Pytorch 函数汇总

目录

torch.cat()

torch.split()

torch.where()

torch.matmul()

torch.expend_as

torch.clamp()

torch.nn.Parameter()


torch.cat()

torch.cat((x,y),dim=1)

对x和y的指定维度进行拼接。

torch.split()

torch.split(x,dims,dim=1)

对指定维度进行分割。

torch.where()

torch.where(a>0,b,c)

如果满足a>0的条件,输出b,否则输出c

torch.matmul()

torch.matmul(a,b),将矩阵a和矩阵b相乘

torch.expend_as

将某一维度进行拓展,代码示例:

import torch
#1
x = torch.randn(2, 1, 1)#为1可以扩展为3和3 
y = torch.randn(2, 3, 3)
x = x.expand_as(y)
print('x :', x.size())
>>> x : torch.Size([2, 3, 3])
#2
x = torch.randn(2, 2, 2)#为2不可以扩展为3和4
y = torch.randn(2, 3, 4)
x = x.expand_as(y)
print('x :', x.size())
>>> RuntimeError: The expanded size of the tensor (4) must match the existing size (2) at non-singleton dimension 2.  Target sizes: [2, 3, 4].

torch.clamp()

torch.clamp(input, min, max, out=None) → Tensor

将输入input张量每个元素的夹紧到区间 [min,max],并返回结果到一个新张量。

操作定义如下:

      | min, if x_i < min
y_i = | x_i, if min <= x_i <= max
      | max, if x_i > max

torch.nn.Parameter()

作用是在网络中自定义一个可以训练的参数。
一般格式如:

self.gamma = nn.Parameter(torch.zeros(1))

默认requires_grad_ = True
特别地:
torch.empty() 创建任意数据类型的张量

torch.tensor() 只创建torch.FloatTensor类型的张量

所以torch.Tensor() 是torch.empty() 的特例

empty()返回一个包含未初始化数据的张量。使用参数可以指定张量的形状、输出张量、数据类型。

举例

empty = torch.empty(2, 3)  # Returns a tensor filled with uninitialized data.
print(empty)  # 每一次跑的结果都不一样
# tensor([[2.6999e-06, 1.7377e-04, 1.0431e-08],
#         [4.0046e-11, 1.4013e-45, 2.6407e-06]])
 
===========================================================================
 
tensor = torch.tensor([2, 8])  # Constructs a tensor with data
print(tensor)  # tensor([2, 8])
 

文章持续更新中,敬请关注。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值