东方耀AI技术分享

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
热搜: 活动 交友 discuz
查看: 2072|回复: 0

[PyTorch] 09、pytorch中(指数与L2)归一化的几种实现

[复制链接]

1365

主题

1856

帖子

1万

积分

管理员

Rank: 10Rank: 10Rank: 10

积分
14429
QQ
发表于 2020-6-5 10:26:11 | 显示全部楼层 |阅读模式
09、pytorch中(指数与L2)归一化的几种实现



  1. # -*- coding: utf-8 -*-
  2. __author__ = u'东方耀 微信:dfy_88888'
  3. __date__ = '2020/6/5 上午8:41'
  4. __product__ = 'PyCharm'
  5. __filename__ = 'dfy_demo01'


  6. import torch
  7. import torch.nn.functional as F
  8. import numpy as np
  9. import math

  10. # 需要对特征向量进行归一化 p=2就是l2归一化吗?
  11. # x = F.normalize(x, p=2, dim=1)


  12. def l2_norm(input, axis=1):
  13.     norm = torch.norm(input, p=2, dim=axis, keepdim=True)
  14.     print("欧式距离p=2:", norm)
  15.     output = torch.div(input, norm)
  16.     return output

  17. a = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32)
  18. t = torch.from_numpy(a)

  19. print(t, t.size())
  20. # 2*3  2个样本 特征向量维度为3
  21. # softmax本身就是指数的归一化函数
  22. print("指数的归一化:", F.softmax(t, dim=1))
  23. print("指数的归一化后取对数", F.log_softmax(t, dim=1))
  24. #
  25. # 下面自己用数学公式实现
  26. fenzi = math.exp(1)
  27. fenmu = math.exp(1) + math.exp(2) + math.exp(3)
  28. print(fenzi / fenmu)
  29. print(math.log(fenzi /fenmu))

  30. print("*"*50)
  31. # dim=1 还是列的方向  就是一行
  32. print("L2的归一化:", F.normalize(t, p=2, dim=1))
  33. print("手动计算:", 1.0 / (math.sqrt(1*1 + 2*2 + 3*3)))

  34. print(l2_norm(t, axis=1))
  35. # torch.norm 计算各种距离 p=2欧式距离
  36. # torch.nn.functional.normalize()  归一化
  37. # pytorch中(指数与L2)归一化的几种实现

复制代码






让天下人人学会人工智能!人工智能的前景一片大好!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|人工智能工程师的摇篮 ( 湘ICP备2020019608号-1 )

GMT+8, 2024-4-19 08:50 , Processed in 0.188765 second(s), 19 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表