动手学习深度学习 | 部分python函数详解

(1):维度dim,保持原有维度keepdim

下面通过图像的形式直观的展示了这两个参数的作用。

X = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(X.sum(dim=0, keepdim=True))
print(X.sum(dim=1, keepdim=True))
print(X.sum(dim=0, keepdim=False))
print(X.sum(dim=1, keepdim=False))


(2):view函数的用法

view函数的用法如下所示,就是用于改变tensor的维度。其中-1表示当前维度会根据其余指定维度自适应得到。

y = torch.LongTensor([0, 2])
print(y,y.shape)
print(y.view(-1, 1),y.view(-1, 1).shape)

#-------------------------
tensor([0, 2]) torch.Size([2])
tensor([[0],
        [2]]) torch.Size([2, 1])

(3):gather函数的用法

ganther函数的用法如下所示,用于批量取出目标tensor中对应维度的数据。

y_hat = torch.tensor([[0.1, 0.3, 0.6], [0.3, 0.2, 0.5]])
y1 = torch.LongTensor([[0, 1, 1]])
y2 = torch.LongTensor([[1,2]])
print(y_hat.gather(0, y1.view(1, -1)))
print(y_hat.gather(1, y2.view(-1, 1)))

#---------------------
tensor([[0.1000, 0.2000, 0.5000]])
tensor([[0.3000],
        [0.5000]])


(4):argmax函数的用法
y_hat = torch.tensor([[0.1, 0.3, 0.6], [0.3, 0.2, 0.5]])
print(y_hat.argmax(dim=0))
print(y_hat.argmax(dim=1))
#-----------------------
tensor([1, 0, 0])
tensor([2, 2])

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yuanCruise

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值