|
分别用纯Python、TensorFlow1.X、2.X、PyTorch1.3实现同一个计算(方便比较)
- # -*- coding: utf-8 -*-
- __author__ = u'东方耀 微信:dfy_88888'
- __date__ = '2019/10/26 17:18'
- __product__ = 'PyCharm'
- __filename__ = 'tensorflow_vs_pytorch'
- import tensorflow as tf
- import torch
- import sys
- # 1.14.0
- print(tf.__version__)
- # 1.3.0
- print(torch.__version__)
- # python 3.6.8
- print(sys.version)
- # 实现同一个操作 计算 1+ 1/2 + 1/2^2 + 1/2^3 + ....+ 1/2^50
- # 纯python实现
- x = 0.0
- for i in range(51):
- x = x + 1.0 / (2**i)
- print(x)
- # TensorFlow实现
- x = tf.Variable(initial_value=0.0)
- y = tf.Variable(initial_value=1.0)
- # x = x+y
- add_op = x.assign_add(y)
- # y = y/2
- div_op = y.assign(y/2)
- with tf.Session() as sess:
- sess.run(tf.global_variables_initializer())
- for i in range(51):
- sess.run(add_op)
- sess.run(div_op)
- print('result:', sess.run(x))
- # PyTorch实现
- x = torch.tensor([0.0])
- y = torch.tensor([1.0])
- for i in range(51):
- x = x+y
- y = y/2
- print('result_torch:', x)
- # TensorFlow 2.0实现 打开eager mode动态图功能(不可逆的 打开后无法关闭)
- tf.enable_eager_execution()
- # ValueError: tf.enable_eager_execution must be called at program startup.
- x = tf.constant(value=0.0)
- y = tf.constant(value=1.0)
- for i in range(51):
- x = x+y
- y = y/2
- print('result tf2.0 eager mode:', x.numpy())
复制代码
|
|