东方耀AI技术分享

标题: 分别用纯Python、TensorFlow1.X、2.X、PyTorch1.3实现同一个计算(... [打印本页]

作者: 东方耀    时间: 2019-10-26 17:59
标题: 分别用纯Python、TensorFlow1.X、2.X、PyTorch1.3实现同一个计算(...
分别用纯Python、TensorFlow1.X、2.X、PyTorch1.3实现同一个计算(方便比较)


  1. # -*- coding: utf-8 -*-
  2. __author__ = u'东方耀 微信:dfy_88888'
  3. __date__ = '2019/10/26 17:18'
  4. __product__ = 'PyCharm'
  5. __filename__ = 'tensorflow_vs_pytorch'

  6. import tensorflow as tf
  7. import torch
  8. import sys
  9. # 1.14.0
  10. print(tf.__version__)
  11. # 1.3.0
  12. print(torch.__version__)
  13. # python 3.6.8
  14. print(sys.version)
  15. # 实现同一个操作  计算 1+ 1/2 + 1/2^2 + 1/2^3 + ....+ 1/2^50
  16. # 纯python实现
  17. x = 0.0
  18. for i in range(51):
  19.     x = x + 1.0 / (2**i)
  20. print(x)

  21. # TensorFlow实现
  22. x = tf.Variable(initial_value=0.0)
  23. y = tf.Variable(initial_value=1.0)
  24. # x = x+y
  25. add_op = x.assign_add(y)
  26. # y = y/2
  27. div_op = y.assign(y/2)

  28. with tf.Session() as sess:
  29.     sess.run(tf.global_variables_initializer())
  30.     for i in range(51):
  31.         sess.run(add_op)
  32.         sess.run(div_op)
  33.     print('result:', sess.run(x))

  34. # PyTorch实现
  35. x = torch.tensor([0.0])
  36. y = torch.tensor([1.0])
  37. for i in range(51):
  38.     x = x+y
  39.     y = y/2
  40. print('result_torch:', x)


  41. # TensorFlow 2.0实现 打开eager mode动态图功能(不可逆的 打开后无法关闭)
  42. tf.enable_eager_execution()
  43. # ValueError: tf.enable_eager_execution must be called at program startup.
  44. x = tf.constant(value=0.0)
  45. y = tf.constant(value=1.0)
  46. for i in range(51):
  47.     x = x+y
  48.     y = y/2
  49. print('result tf2.0 eager mode:', x.numpy())




复制代码







欢迎光临 东方耀AI技术分享 (http://www.ai111.vip/) Powered by Discuz! X3.4