torch.renorm的重写

  1. torch.renorm(input, p, dim, maxnorm, *, out=None) → Tensor
    v a l u e = { x _ s u b v e c t o r p _ n o r m ( x _ s u b v e c t o r ) where p_norm > max_norm p _ n o r m ( x _ s u b v e c t o r ) otherwise value = \begin{cases} \frac{x\_subvector}{p\_norm(x\_subvector)}\quad \text{where p\_norm > max\_norm\\}\\ p\_norm(x\_subvector)\quad \text{otherwise}\\ \end{cases} value={p_norm(x_subvector)x_subvectorwhere p_norm > max_normp_norm(x_subvector)otherwise

    即求得x的范数后,如果范数大于max_norm,则进行截断;将x值与max_norm做商,作为新的范数;如果小于max_norm,即不做处理;

   feat = torch.Tensor([[1,2,3],[4,5,6],[7,8,9]])
  feat_r = feat.renorm(2, 0, 1e-5).mul(1e5)
  print(f"renorm feat_r: {feat_r}")
  print(f"----")
  b_l2 = np.linalg.norm(feat, axis=1)
  #b_l2 = b_l2.reshape(3,1)

  # 这里调整 numpy 对应除法,需要给l2范数增加一个维度,或者使用转置矩阵(注释掉的代码)
  b_l2 = np.expand_dims(b_l2, 1)
  print(b_l2,'\n')
  max_num_val = 1e-5
  b_l2[b_l2<=max_num_val] = 1
  #res = (b.T/b_l2).T
  res = feat/b_l2
  print(res)

  print(f"----")
  # l2_t = torch.linalg.norm(feat, ord=2, dim=1)
  l2_t = feat.norm(2, 1)
  print(f"l2_t: {l2_t}")
  l2_tran = l2_t.unsqueeze(dim=0).t()
  l2_tran[l2_tran <= max_num_val] = 1
  res = feat/l2_tran
  print(res)

ref:
关于torch.renorm的一些理解和np复写

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值